我使用一个临时文件在两个进程之间交换数据:
为了演示起见,下面是一段代码,它使用一个子进程来增加一个数字:
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正如您在上面看到的,我使用tempfile.NamedTemporaryFile(delete=False)来创建文件,然后关闭它,然后重新打开它。我的问题是:
这是可靠的,还是在我关闭临时文件后,操作系统会删除它?或者可能该文件被重用到另一个需要临时文件的进程?有什么东西会毁了我的数据吗?
发布于 2018-07-15 17:41:19
文件上没有说。操作系统可能会在一段时间后自动删除文件,这取决于如何设置文件和使用什么目录。如果您想要持久化,请使用持久性代码:使用常规文件,而不是临时文件。
https://stackoverflow.com/questions/51350603
复制相似问题