How do I run a Python program in the Vim editor without closing it?

46 Views Asked by At

I found the answer to my question last night: How do I run the simple Hello world in python in the Vim editor without closing Vim? but I cannot find it today. It was real simple, something like :!python helloworld.py to do but everything I try today does not work and my searches in Google do not turn up the same as I got last night.

2

There are 2 best solutions below

0
Bernardo On

In vim you can run commmands inside the editor using the :! terminology. So for example, a normal python script would be executed using:

python script_name.py

From inside vim you can run it by doing the following:

:!python script.name.py

Hope that's helpful.

0
Friedrich On

You can take advantage of Vim substituting % in the command line with the current buffer's file name (see :help c_%) and do just

:!python %

I find myself running :!./% quite a lot when writing any kind of interpreted language.

This uses :! to run the following stuff in the shell. The command to run is ./% which is ./ for the current directory % is the file name as we know.

There are three preconditions:

  • Vim's working directory needs to be where the file resides
  • the file has the executable property set (:!chmod +x % to set it without leaving Vim)
  • the file has a shebang that points to the interpreter, e.g. #!/usr/bin/env python as its first line