简体   繁体   中英

How to create a mapping to execute python code from Vim?

Here's the steps I follow to execute python code from Vim:

  1. I write a python source code using Vim
  2. I execute it via :w !python

and I'd like a shorter way to execute the code, so I searched the Internet for a shortcut key such as this map:

autocmd FileType python nnoremap <buffer> <F9> :exec '!python' shellescape(@%, 1)<cr>

and added it to the _vimrc file. But when I hit F9 , the following error message appears:

在此处输入图片说明

Here is the relevant text in the image above:

python: can't open file ''D:/py2.py'': [Errno 22] Invalid argument
shell returned 2.

I have already searched the Internet, but I have not got any result.

I use gVim 8.0 in Windows 10, if that helps.

Interacting with command-line through vim, the much preferred way would be with exclamation.
Instead of:

:exec '!python' shellescape(@%, 1)<cr>

Try doing the easy way:

:update<bar>!python %<CR>

here in the above code:
update save file if modified ( preferred ) or can also use w .
<bar> pipe commands.
!python % will run the file as python filename .

So basically, put this in your .vimrc file, and that'll do it:

autocmd FileType python nnoremap <buffer> <F9> :update<bar>!python %<CR>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM