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
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()
3 Comments
jl6
Is Vim guaranteed to flush to the file before call() returns?
Jens Wirth
@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.
Jens Wirth
@jl6: btw, I would prefer James answer. It's pretty convenient.
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!