The python docs for tempfile.NamedTemporaryFile say:
Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
I have a program that's invoked as prog input.txt, that I can't touch. I want to write a python function to give this a string.
Here's various approaches that don't quite work:
from tempfile import NamedTemporaryFile
Not obvious if legal on windows
with NamedTemporaryFile() as f: f.write(contents) subprocess.check_call(['prog', f.name]) # legal on windows?Might delete the file too early
with NamedTemporaryFile() as f: f.write(contents) f.close() # does this delete the file? subprocess.check_call(['prog', f.name])Doesn't clean up properly
with NamedTemporaryFile(delete=False) as f: f.write(contents) # if this fails, we never clean up! try: subprocess.check_call(['prog', f.name]) finally: os.unlink(f.name)A little ugly
f = NamedTemporaryFile(delete=False) try: with f: f.write(contents) subprocess.check_call(['prog', f.name]) finally: os.unlink(f.name)
Which of these are correct?