jl6
jl6

Reputation: 6394

How can I call Vim from Python?

I would like a Python script to prompt me for a string, but I would like to use Vim to enter that string (because the string might be long and I want to use Vim's editing capability while entering it).

Upvotes: 4

Views: 243

Answers (2)

Jens Wirth
Jens Wirth

Reputation: 17460

You can call vim with a file path of your choice:

from subprocess import call
call(["vim","hello.txt"])

Now you can use this file as your string:

file = open("hello.txt", "r")
aString = file.read()

Upvotes: 4

James Mills
James Mills

Reputation: 19030

Solution:

#!/usr/bin/env python


from __future__ import print_function

from os import unlink
from tempfile import mkstemp
from subprocess import Popen


def callvim():
    fd, filename = mkstemp()

    p = Popen(["/usr/bin/vim", filename])
    p.wait()

    try:
        return open(filename, "r").read()
    finally:
        unlink(filename)


data = callvim()
print(data)

Example:

$ python foo.py 
This is a big string.

This is another line in the string.

Bye!

Upvotes: 3

Related Questions