Executing just multiple python lines in VIM

51 Views Asked by At

My code is:

stuff = 'bla'
print(stuff)

I'm using the vim editor on linux mint to learn it.

So my question is:

I also have other code snippets above. But I want to for example try this two codes of lines out in the vim editor. Is there a way that i can execute that? Like in vscode where i can "Run Selection/Line in Python Terminal) with Shift + Enter.

Thanks for the help.

2

There are 2 best solutions below

0
Friedrich On BEST ANSWER

Vim also sports a :terminal command. Looking at :help :terminal will reveal the following information:

:[range]ter[minal] [options] [command]
            Open a new terminal window.

            If [command] is provided run it as a job and connect
            the input and output to the terminal.

            [...]

            If [range] is given the specified lines are used as
            input for the job.  It will not be possible to type
            keys in the terminal window.

This looks pretty complete: you can run a command (here: your Python interpreter) in a terminal, feeding it some lines from your buffer as input.

You would enter linewise Visual mode with ShiftV, select the lines to run and call

:'<,'>terminal python

where '<,'> stands for the current visual selection. Vim will already populate your command line with this when you type : in Visual mode.

On hitting enter, Vim will open a terminal window which will show the output (if any) of the Python code you just ran. Type :q to close the terminal and return to your normal editing.

For convenience, consider writing a command or a mapping to quickly run Python code. The following line will define a :Python command that runs the current visual selection or the whole buffer if nothing is selected:

:command -range=% Python <line1>,<line2>terminal python
0
Daan Koetsenruijter On

First, to be clear: VIM can not execute python code. You need a python interpreter for this. For example, an IPython shell.

Second, to execute python code written in the VIM text editor you can use IPython and a vim plugin, vim-ipython-cell.

This plugin allows Jupyter Notebook style cell execution using a custom defined ipython shell. I have been working with this since a while and I can recommend.

It builds on a more basic vim plugin vim-slime, which technically can also do what you want.

Another option, which I haven't tried, is nvim-ipy.