简体   繁体   中英

Execute line(s) of python script in Vim

I just started using Vim for my main IDE, and one of my frequently used functions in the previous IDE is "execute selection in python".

I've learned that there are two ways in executing the code in python, one is :python3 {expression} and the other one is :w python3

What I want to do is execute selected line(s) of the script in vim without refreshing(closing) the python console.

It looks like :python3 {expression} does not close the python console, so after I used :python3 a=3 , command :python3 print(a) returns proper value 3 . However, I think this function does not have a "selection feature" in it. Although :help python shows the [range] argument, but I can't understand how to use it.

On the other hand, the second function has the selection feature (ex. :1,3w !python3 ) but it seems the python console is refreshed(=closed) everytime I use the function.

I guess adding simple function to .vimrc will do for my purpose but couldn't find one. Any help will be really appreciated!

Found the answer!

I solved it by making a simple custom commands.

python3 << EOL
import vim

def ExecuteSelectedLine(l1, l2):
    for i in range(l1-1,l2):
        print(">>" + vim.current.buffer[i])
        exec(vim.current.buffer[i],globals())
EOL
command! -range Eval <line1>,<line2> python3 ExecuteSelectedLine(<line1>, <line2>)

How to use

  • Run only 1st to 3rd lines of script in python :1,3Eval
  • Run the current line in python :Eval
  • Run visually selected parts of script in python :'<,'>Eval

range selection works with -range option, and using python's "exec" function with globals() option, persistency remains (no refreshing).

I guess my coding style, trying different code snippets in a console and finalizing the main script, is a weird way to code since I couldn't find similar attempts in the communities.

Thanks to all!

I don't understand the question. Command

:1,3w !python3

Should do the trick, what do you exactly mean by saying "python console is refreshing everytime I use the function"? If you mean, that it waits for enter key to be pressed to go back to vim, it is just natural.

You may also use:

:'<,'>w !python3

While previously using Visual Mode to select certain block of code. Do you want to execute the code in a new terminal window?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM