4

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).

2 Answers 2

4

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Is Vim guaranteed to flush to the file before call() returns?
@jl6: nice question. I don't think there is a guarantee because it is the operating system's cup of tea when the data is physically flushed to the file. But I assume that you will call open() after call() and that the OS is fair enough to finish the write action before opening the file in read mode.
@jl6: btw, I would prefer James answer. It's pretty convenient.
3

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.