Home > python, vim > [vim] run current file with Python

[vim] run current file with Python

You use (neo)vim for editing your Python code and you want to execute the source code in your editor. The output of the script should appear in the editor.

I came up with a dynamic solution, i.e. the interpreter is taken from the first line of the code. If you specified “#!/usr/bin/env python2“, then python2 is used; if you have “#!/usr/bin/env python3“, then python3 is used.

But what if you use Anaconda and you have for instance “#!/opt/anaconda3/bin/python3” in the first line? Then simply this interpreter is used.

Here is the snippet from my config file:

" run python script {{{
    function! RunWithPython()
        let first = getline(1)
        let first = substitute(first, "^#!", "", "")
        let first = substitute(first, "\n", "", "")
        let exe = ""    " the Python binary to call

        if first =~ "/usr/bin/env "
            let exe = split(first)[-1]
        elseif first == "/opt/anaconda3/bin/python3"
            let exe = first
        if exe == ""
            echo "Error: unknown Python interpreter in the first line."
        " echo exe
        echo system(exe . " " . expand('%'))

    au FileType python nnoremap <buffer> <F9> :call RunWithPython()<cr>
" }}}

If you want to use Anaconda, then simply customize line 10.

Categories: python, vim Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: