Commenters and the other answer have pointed out how to run a file from vim. But they glossed over some really powerful possibilities. I'd like to explain how some of those work in more detail.
The simplest possible way of running a python script in vim, is to just call the python interpreter on the file, e.g.
:!python %
or, as I prefer to do to make sure there are no unsaved changes,
:w | !python %
But it is not even necessary to have a file to run a python script in vim. The reason why is because :w
!= save! :w
means write, and if no argument is provided, it happens to write to the file you are editing. However, you can write to STDOUT, to another file, or even to another program. So if you'd like to run your buffer as python code without having a file to save and run, you may simply do:
:w !python
This meanse write the current buffer into the external program "python". This literally just sends the contents of your buffer directly to python.
Now here's where it gets really cool. In vim, :w
is an "ex command", e.g. a command that you run from the vim command line that originally came from ex, a very old line based unix text editor. The awesome thing about ex commands is that since they are all line based, you can directly state which lines you would like the command to apply to. For example:
:2w myfile.txt
will write only line two to the file "myfile.txt". You can even supply a range, e.g.
:2,7w myfile.txt
will write lines 2-7 to "myfile.txt". This means that using your example, we can run
:1w !python
to run just
print('hello')
To make this more convenient, you can use visual mode to select every line you would like to run, which will automatically fill in the right range for you. This will look like
:'<,'>w !python
To make this more convenient, I would recommend adding something like
xnoremap <leader>p :w !python<cr>
to your .vimrc
. Then you can visually select whatever you want and run it as python code by typing
\p
(replace \
with whatever you have set up as your leader). You could also do
nnoremap <leader>p :w !python<cr>
or
nnoremap <leader>p :w | !python %<cr>
depending on whether you want to save to a file or not.
:!python3 test.py
. 2):!python3 -c "print('hello')"
. – Kershaw