1

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:

enter image description here

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.

2
  • Screenshots are evil (especially links to screenshots). Please copy-paste (or manually write) error in your question. Commented Oct 12, 2016 at 10:58
  • I added the message manually.@Jérôme Commented Oct 12, 2016 at 11:30

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

4 Comments

What should I add to the _vimrc file?Sorry for I can not the ":update<bar>!python %<CR>" ’s meaning you have post.Is this sentence means that I should type :w !python at the bottom of the vim window?
I am sorry .The former response lost a "understand".
autocmd FileType python nnoremap <buffer> <F9> :update<bar>!python %<CR>, put this in you .vimrc file, and you are good to go.
,Thank you .After adding the code you gave,the cmd returns good result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.