I want to replicate the functionality that happens when you do something like 'git commit'. It opens up your editor and you type some stuff and then save/exit to hand off that file back to the script that launched the editor.
How would I implement this functionality in Python?
EDIT:
Thanks for the suggestions, here's a working example based on the answers:
import os, subprocess, tempfile
(fd, path) = tempfile.mkstemp()
fp = os.fdopen(fd, 'w')
fp.write('default')
fp.close()
editor = os.getenv('EDITOR', 'vi')
print(editor, path)
subprocess.call('%s %s' % (editor, path), shell=True)
with open(path, 'r') as f:
print(f.read())
os.unlink(path)
The usual case is to:
So something like this:
import os, subprocess, tempfile
f, fname = tempfile.mkstemp()
f.write('default')
f.close()
cmd = os.environ.get('EDITOR', 'vi') + ' ' + fname
subprocess.call(cmd, shell=True)
with open(fname, 'r') as f:
#read file
os.unlink(fname)
Save the text data you intend to be modified to a temporary file, open the editor (vi) as an external process pointing to that file, using os.system - or subprocess.Popen if you need more control over it, and read the temporary file back.
I'd advise you to open vi by default, but respect the contents of the "VISUAL" environment variable.
import os
name = os.tmpnam()
editor = "vi" if not ["VISUAL"] in os.environ else os.environ["VISUAL"]
os.system("%s %s" % (editor, name))
data = open(name).read()
os.unlink(name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With