Running Python code in Vim

I write Python code using Vim, and every time I want to run my code, I type this inside Vim:

:w !python 

This is frustrating, so I was looking for a faster method to run Python code inside Vim. Is it possible to execute Python scripts from a terminal? I am using Linux.

+82
python vim
Sep 22 '13 at 20:35
source share
16 answers

how about adding autocmd when FileType python autocmd create a mapping:

 nnoremap <buffer> <F9> :exec '!python' shellescape(@%, 1)<cr> 

then you can press <F9> to execute the current buffer using python

+116
Sep 22 '13 at 20:38
source share

I have this in the .vimrc file:

 imap <F5> <Esc>:w<CR>:!clear;python %<CR> 

When I finished editing the Python script, I just press <F5> . The script is saved and then executed on a blank screen.

+24
Jul 30 '14 at 13:55
source share

Just go into normal mode by pressing <esc> and typing:

 ! clear; python % 

enter image description here

Step by step explanation:

! allows you to run a terminal command

clear screen of your terminal

; finishes the first command, allowing you to enter the second command

python will use python to run your script (it can be replaced with ruby for example)

% matches current file name, passing it as parameter to python command

+17
Sep 05 '18 at 13:22
source share

I prefer Python output redirected to a new Vim window (and if you leave this window open, update its contents the next time you execute Python code using this function):

 " Bind F5 to save file if modified and execute python script in a buffer. nnoremap <silent> <F5> :call SaveAndExecutePython()<CR> vnoremap <silent> <F5> :<Cu>call SaveAndExecutePython()<CR> function! SaveAndExecutePython() " SOURCE [reusable window]: https://github.com/fatih/vim-go/blob/master/autoload/go/ui.vim " save and reload current file silent execute "update | edit" " get file path of current file let s:current_buffer_file_path = expand("%") let s:output_buffer_name = "Python" let s:output_buffer_filetype = "output" " reuse existing buffer window if it exists otherwise create a new one if !exists("s:buf_nr") || !bufexists(s:buf_nr) silent execute 'botright new ' . s:output_buffer_name let s:buf_nr = bufnr('%') elseif bufwinnr(s:buf_nr) == -1 silent execute 'botright new' silent execute s:buf_nr . 'buffer' elseif bufwinnr(s:buf_nr) != bufwinnr('%') silent execute bufwinnr(s:buf_nr) . 'wincmd w' endif silent execute "setlocal filetype=" . s:output_buffer_filetype setlocal bufhidden=delete setlocal buftype=nofile setlocal noswapfile setlocal nobuflisted setlocal winfixheight setlocal cursorline " make it easy to distinguish setlocal nonumber setlocal norelativenumber setlocal showbreak="" " clear the buffer setlocal noreadonly setlocal modifiable %delete _ " add the console output silent execute ".!python " . shellescape(s:current_buffer_file_path, 1) " resize window to content length " Note: This is annoying because if you print a lot of lines then your code buffer is forced to a height of one line every time you run this function. " However without this line the buffer starts off as a default size and if you resize the buffer then it keeps that custom size after repeated runs of this function. " But if you close the output buffer then it returns to using the default size when its recreated "execute 'resize' . line('$') " make the buffer non modifiable setlocal readonly setlocal nomodifiable endfunction 

It took a lot of effort, so if you feel generous send PayPal . donation :)

+15
Oct 22 '16 at 18:55
source share

Based on the previous answers, if you want to see the code looking at its results, you can find :ter command :ter ( :terminal ) useful.

 autocmd Filetype python nnoremap <buffer> <F5> :w<CR>:ter python2 "%"<CR> autocmd Filetype python nnoremap <buffer> <F6> :w<CR>:vert ter python3 "%"<CR> 

Using vert in the second line runs the code vertically, not horizontally.

The disadvantage of this is that if you do not close the split window in which the code was executed, you will have many splits after several starts (which does not happen in the original Python IDLE, where the same output window is reused).

(I keep these lines inside /home/user/.vimrc )

+6
Nov 27 '18 at 2:21
source share

Keep in mind that you can repeat the last used command with @: so all you need to repeat is two characters.

Or you can save the w !python string in one of the registers (for example, "a for example), and then press :<CR>a<CR> to paste the contents of register a into the command line and run it.

Or you can do what I'm doing and map <leader>z to :!python %<CR> to run the current file.

+5
Sep 22 '13 at 21:09 on
source share

If you don't want to print " :exec python file.py " every time, use this:

 nnoremap <F9> :echo system('python2 "' . expand('%') . '"')<cr> nnoremap <F10> :echo system('python3 "' . expand('%') . '"')<cr> 

This also did not spoil my powerline / vim airline status bar.

+2
May 17 '16 at 20:29
source share

A simple method would be to enter : in normal mode, and then press the up arrow key on the keyboard and press Enter. This will repeat the last entered commands on VIM.

+1
Feb 17 '14 at 10:11
source share

If you want to quickly return to your commands :w , then it's cool to type :w , and then press the up arrow. It will only work through commands starting with w .

+1
Mar 19 '14 at 19:56
source share

For general use (run python / haskell / ruby ​​/ C ++ ... from vim based on filetype ), there is a nice plugin called vim-quickrun . By default, it supports many programming languages. It is also easily customizable, so if necessary, you can define your preferred behavior for any type of file. The github repository does not have a fancy readme, but it is well documented with a doc file.

+1
Jan 28 '15 at 14:13
source share

I have this on my .vimrc:

 "map <F9> :w<CR>:!python %<CR>" 

which saves the current buffer and executes code using only Esc + F9

+1
Dec 08 '15 at 13:39
source share

You can also use skywind3000 / asyncrun.vim . This is similar to what @FocusedWolf has listed.

+1
Jul 07 '19 at 16:54
source share

Conque Shell is required for this .vimrc display, but it replicates the behavior of Geany (and other X editors):

  • Press key to execute
  • Running in gnome-terminal
  • Awaiting confirmation of exit
  • The window closes automatically upon exit

    :let dummy = conque_term#subprocess('gnome-terminal -e "bash -c \"python ' . expand("%") . '; answer=\\\"z\\\"; while [ $answer != \\\"q\\\" ]; do printf \\\"\nexited with code $?, press (q) to quit: \\\"; read -n 1 answer; done; \" "')

0
Sep 24 '14 at 12:43
source share

Instead of putting the command mapping in your .vimrc , put that mapping in your ~/.vim/ftplugin/python.vim (Windows $HOME\vimfiles\ftplugin\python.vim ). If you do not have this file or directories, just create them. Thus, the key is displayed only when opening the .py file or any file with filetype=python , since you will only run this command in Python scripts.

For real display, I like being able to edit in Vim while the script is running. Based on @cazyas answer, I have the ftplugin\python.vim in ftplugin\python.vim (Windows):

 noremap <F5> <Esc>:w<CR>:!START /B python %<CR> 

This will run the current Python script in the background. For Linux, just change this to this:

 noremap <F5> <Esc>:w<CR>:!python % &<CR> 
0
Jan 01 '18 at 17:51
source share

The accepted answer works for me (on Linux), but I wanted this command to also save the buffer before starting, so I changed it a bit:

 nnoremap <buffer> <F9> :w <bar> :exec '!python' shellescape(@%, 1)<cr> 

:w <bar> saves the buffer, then runs the code in it.

0
Aug 08 '19 at 17:30
source share

Place the cursor in the code somewhere. Right-click and select one of the "Select" options to highlight the code. Then press Ctrl: and you will see a new prompt '<,>'

Now enter! python and see if this works.

I just spend days trying to figure out the same problem !!! I used the encoding:

 s='My name' print (s) 

After I pulled out all my hair, I finally got it right.

-one
Aug 11 '14 at 21:50
source share



All Articles