直接从VIM运行Python代码时出现小问题



我希望能够设置热键\,以便能够从VIM编写和运行python脚本,而无需每次都键入

:w
:! python3 file.py

到目前为止,我所做的是将以下内容粘贴到我的vimrc文件中:

"{{{ The following is for sourcing command.vim whenever exists.
" Function to source only if the file command.vim exists
" https://devel.tech/snippets/n/vIIMz8vZ/load-vim-source-files-only-if-they-exist
"
function! SourceIfExists(file)
if filereadable(expand(a:file))
echom a:file . " is about to be sourced."
exe 'source' a:file
endif
endfunction
autocmd BufEnter * call SourceIfExists("command.vim")
" }}}

然后在我的python文件所在的同一目录中,我创建了一个名为command.vim的文件,并在该文件中粘贴以下内容:

noremap <leader><leader> :w <cr> :!python3 % &<cr>

现在,除了以下问题外,这几乎可以完美地工作。假设我想运行以下脚本,我将其称为file.py:

import numpy as np
x = np.linspace(0, 5, 6)
y = np.linspace(6, 10, 5)
print('{}n{}'.format(x, y))

如果我使用:! python3 file.py以标准方式运行它,那么输出如下:

[0. 1. 2. 3. 4. 5.]
[ 6.  7.  8.  9. 10.]
Press ENTER or type command to continue

但是,如果我使用\方法运行相同的脚本,我会得到以下输出:

Press ENTER or type command to continue[0. 1. 2. 3. 4. 5.]
[ 6.  7.  8.  9. 10.]

您可以看到,使用\的脚本输出并不像使用标准命令:! python3 file.py时那样格式化良好。

有人知道怎么解决这个问题吗?

映射的作用:

:w
:!python3 % &

与手动操作不同:

:w
:!python3 file.py

如果你想要与手动方式相同的结果,你只需要做同样的事情:

nnoremap <leader><leader> :w<cr>:!python3 %<cr>

是不必要的&导致了您的问题:它将命令发送到后台,因此Vim认为它已经完成,并收回了对终端的控制。但是后台作业仍然将其输出打印到与Vim相同的终端,结果会一团糟。删除&将修复映射。

顺便说一句,整个command.vim的事情a(毫无用处,b(过于复杂,b(转移注意力。你应该把它从问题中删除……从你的vimrc中删除。

最新更新