Run a Python Script In Vim
Apr 02, 2023
Sometimes its useful, when editing a python script in vim, to quickly run the script to test the output. There are a million reasons to run a python script in vim, and it's easy to do it with the press of a key.
Here's the code to configure vim to run a python file that is in the current buffer with the press of the F5 key.
" Map the F5 key to run a Python script inside Vim.
" We map F5 to a chain of commands here.
" :w saves the file.
" <CR> (carriage return) is like pressing the enter key.
" !clear runs the external clear screen command.
" !python3 % executes the current file with Python.
nnoremap <f5> :w <CR>:!clear <CR>:!python3 % <CR>
If you add the above code to your .vimrc file, which should be located at ~/.vimrc, and have a python script open, pressing F5 will save your file, clear the screen, and display the results of the python output. Getting back to your file is as simple as pressing Enter.