J.Neue
J.Neue

Reputation: 345

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:

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.

Upvotes: 1

Views: 2507

Answers (1)

LycuiD
LycuiD

Reputation: 2575

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>

Upvotes: 2

Related Questions