我正在使用Vim编写Python代码,每次我想运行我的代码时,我都会在Vim中键入以下内容:
:w !python
这很令人沮丧,所以我在寻找一种更快的方法来在Vim中运行Python代码。也许可以从终端执行Python脚本?我使用的是Linux。
发布于 2014-07-30 21:55:33
我的.vimrc文件中有以下内容:
imap <F5> <Esc>:w<CR>:!clear;python %<CR>
当我完成Python脚本的编辑后,我只需按<F5>
。该脚本将被保存,然后在空白屏幕中执行。
发布于 2016-10-23 02:55:10
我更喜欢将Python输出重定向到新的Vim窗口(如果该窗口保持打开状态,则在下次使用此函数执行Python代码时更新其内容):
" Bind F5 to save file if modified and execute python script in a buffer.
nnoremap <silent> <F5> :call SaveAndExecutePython()<CR>
vnoremap <silent> <F5> :<C-u>call SaveAndExecutePython()<CR>
function! SaveAndExecutePython()
" SOURCE [reusable window]: https://github.com/fatih/vim-go/blob/master/autoload/go/ui.vim
" save and reload current file
silent execute "update | edit"
" get file path of current file
let s:current_buffer_file_path = expand("%")
let s:output_buffer_name = "Python"
let s:output_buffer_filetype = "output"
" reuse existing buffer window if it exists otherwise create a new one
if !exists("s:buf_nr") || !bufexists(s:buf_nr)
silent execute 'botright new ' . s:output_buffer_name
let s:buf_nr = bufnr('%')
elseif bufwinnr(s:buf_nr) == -1
silent execute 'botright new'
silent execute s:buf_nr . 'buffer'
elseif bufwinnr(s:buf_nr) != bufwinnr('%')
silent execute bufwinnr(s:buf_nr) . 'wincmd w'
endif
silent execute "setlocal filetype=" . s:output_buffer_filetype
setlocal bufhidden=delete
setlocal buftype=nofile
setlocal noswapfile
setlocal nobuflisted
setlocal winfixheight
setlocal cursorline " make it easy to distinguish
setlocal nonumber
setlocal norelativenumber
setlocal showbreak=""
" clear the buffer
setlocal noreadonly
setlocal modifiable
%delete _
" add the console output
silent execute ".!python " . shellescape(s:current_buffer_file_path, 1)
" resize window to content length
" Note: This is annoying because if you print a lot of lines then your code buffer is forced to a height of one line every time you run this function.
" However without this line the buffer starts off as a default size and if you resize the buffer then it keeps that custom size after repeated runs of this function.
" But if you close the output buffer then it returns to using the default size when its recreated
"execute 'resize' . line('$')
" make the buffer non modifiable
setlocal readonly
setlocal nomodifiable
endfunction
发布于 2018-11-27 10:21:02
在前面答案的基础上,如果你想在查看输出的同时查看代码,你可以发现:ter
(:terminal
)命令很有用。
autocmd Filetype python nnoremap <buffer> <F5> :w<CR>:ter python2 "%"<CR>
autocmd Filetype python nnoremap <buffer> <F6> :w<CR>:vert ter python3 "%"<CR>
在第二行使用vert
以垂直拆分而不是水平拆分的方式运行代码。
它的缺点是,如果不关闭运行代码的拆分窗口,则在多次运行后会有许多拆分(这在原始python空闲中不会发生,因为相同的输出窗口会被重用)。
(我将这几行代码保留在/home/user/.vimrc
中)
https://stackoverflow.com/questions/18948491
复制相似问题