I am writing Python code using Vim, and every time I want to run my code, I type this inside Vim:
:w !python
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.
vimrc options. Vim as a Python IDE shows a slew of plugins and configuration options for coding with Python in Vim. This repository's folder with Vimrc files has example configurations that are well commented and easy to learn from.
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!
Write Your Python Script To write in the vim editor, press i to switch to insert mode. Write the best python script in the world. Press esc to leave the editing mode. Write the command :wq to save and quite the vim editor ( w for write and q for quit ).
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>
then you could press <F9>
to execute the current buffer with python
Explanation:
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. The 1
means with a backslashTL;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
Just go to normal mode by pressing <esc>
and type:
! clear; python %
Step by step explanation:
!
allows you to run a terminal command
clear
will empty your terminal screen
;
ends the first command, allowing you to introduce a second command
python
will use python to run your script (it could be replaced withruby
for example)
%
concats the current filename, passing it as a parameter to thepython
command
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With