在 Vim 中运行 Python 代码
我正在使用 Vim 编写 Python 代码,每次我想运行我的代码时,我都会在 Vim 中输入:
I am writing Python code using Vim, and every time I want to run my code, I type this inside Vim:
:w !python
这令人沮丧,所以我正在寻找一种更快的方法来在 Vim 中运行 Python 代码.也许从终端执行 Python 脚本?我使用的是 Linux.
This gets frustrating, so I was looking for a quicker method to run Python code inside Vim. Executing Python scripts from a terminal maybe? I am using Linux.
如何将 autocmd
添加到您的 ~/.vimrc
文件中,创建一个映射:
How about adding an autocmd
to your ~/.vimrc
-file, creating a mapping:
autocmd FileType python map <buffer> <F9> :w<CR>:exec '!python3' shellescape(@%, 1)<CR>
autocmd FileType python imap <buffer> <F9> <esc>:w<CR>:exec '!python3' shellescape(@%, 1)<CR>
然后你可以按
用 python
说明:
-
autocmd
:Vim 将在{event}
上自动执行的命令(这里:如果你打开一个 python 文件) -
[i]map
:在插入/正常模式下创建
的键盘快捷键 -
:如果打开了多个缓冲区/文件:只使用活动的一个 -
:退出插入模式 -
:w
:保存您的文件 -
!
:在你的 shell 中运行以下命令(试试:!ls
) -
%
:由活动缓冲区的文件名替换.但是因为它可能包含空格和其他坏"的东西,所以最好不要写:python %
,而是使用: -
shellescape
:转义特殊字符.1
表示带反斜杠
-
autocmd
: command that Vim will execute automatically on{event}
(here: if you open a python file) -
[i]map
: creates a keyboard shortcut to<F9>
in insert/normal mode -
<buffer>
: If multiple buffers/files are open: just use the active one -
<esc>
: leaving insert mode -
:w<CR>
: saves your file -
!
: runs the following command in your shell (try:!ls
) -
%
: is replaced by the filename of your active buffer. But since it can contain things like whitespace and other "bad" stuff it is better practise not to write:python %
, but use: -
shellescape
: escape the special characters. The1
means with a backslash
TL;DR:第一行将在正常模式下工作,一旦您按下 <F9>
,它首先保存您的文件,然后使用 python 运行该文件.第二个做同样的事情,但首先离开插入模式
TL;DR: The first line will work in normal mode and once you press <F9>
it first saves your file and then run the file with python.
The second does the same thing, but leaves insert mode first