Opening vi from Python
python
Solution
The usual case is to:
- Create a temporary file, write default contents to it
- Launch the command stored in the environment variable "EDITOR". This usually is a shell command, so it might contain arguments -> run it thourgh the shell or parse it accordingly
- Once the process terminates, read back temporary file
- Remove temporary file
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)
Problem
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) ```