I have been successful in finding code for spawning a vim editor and creating a tempfile from a python script. The code is here, I found it here: call up an EDITOR (vim) from a python script
import sys, tempfile, os
from subprocess import call
EDITOR = os.environ.get('EDITOR','vim')
initial_message = ""
with tempfile.NamedTemporaryFile(suffix=".tmp") as tempfile:
tempfile.write(initial_message)
tempfile.flush()
call([EDITOR, tempfile.name])
The problem I having is that I cannot access the contents of the tempfile after I quit the editor.
tempfile
<closed file '<fdopen>', mode 'w+b' at 0x87c47b0>
tempfile.readline()
I get
ValueError: I/O operation on closed file
I did:
myfile = open(tempfile.name)
IOError: [Errno 2] No such file or directory: '/tmp/tmp7VKzfl.tmp'
How would I access the file in a python script once it has been edited with the editor?
Thank you
Everything inside a
withblock is scoped. If you create the temporary file with thewithstatement, it will not be available after the block ends.You need to read the tempfile contents inside the
withblock, or use another syntax to create the temporary file, e.g.:If you do want to automatically close the file after your block, but still be able to re-open it, pass
delete=Falseto theNamedTemporaryFileconstructor (else it will be deleted after closing):Btw, you might want to use envoy to run subprocesses, nice library 🙂