I'm using a temporary file to exchange data between two processes:
- I create a temporary file and write some data into it
- I start a subprocess that reads and modifies the file
- I read the result from the file
For demonstration purposes, here's a piece of code that uses a subprocess to increment a number:
import subprocess
import sys
import tempfile
# create the file and write the data into it
with tempfile.NamedTemporaryFile('w', delete=False) as file_:
file_.write('5') # input: 5
path = file_.name
# start the subprocess
code = r"""with open(r'{path}', 'r+') as f:
num = int(f.read())
f.seek(0)
f.write(str(num + 1))""".format(path=path)
proc = subprocess.Popen([sys.executable, '-c', code])
proc.wait()
# read the result from the file
with open(path) as file_:
print(file_.read()) # output: 6
As you can see above, I've used tempfile.NamedTemporaryFile(delete=False)
to create the file, then closed it and later reopened it.
My question is:
Is this reliable, or is it possible that the operating system deletes the temporary file after I close it? Or perhaps it's possible that the file is reused for another process that needs a temporary file? Is there any chance that something will destroy my data?