Search code examples
pythonfilevimtemporary-files

Vim Editor in python script tempfile


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


Solution

  • Everything inside a with block is scoped. If you create the temporary file with the with statement, it will not be available after the block ends.

    You need to read the tempfile contents inside the with block, or use another syntax to create the temporary file, e.g.:

    tempfile = NamedTemporaryFile(suffix=".tmp")
    # do stuff
    tempfile.close()
    

    If you do want to automatically close the file after your block, but still be able to re-open it, pass delete=False to the NamedTemporaryFile constructor (else it will be deleted after closing):

    with tempfile.NamedTemporaryFile(suffix=".tmp", delete=False) as tempfile:
    

    Btw, you might want to use envoy to run subprocesses, nice library :)