我正在使用一个临时文件在两个进程之间交换数据:
出于演示目的,下面是一段代码,它使用子进程递增一个数字:
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
正如您在上面看到的,我使用^{
这是可靠的,还是操作系统可能在我关闭临时文件后删除它?或者有可能该文件被重用为另一个需要临时文件的进程?有没有可能有什么东西会破坏我的数据?你知道吗
文件上没有说。操作系统可能会自动 删除文件一段时间后,取决于任何数量的事情 它是如何设置的,使用什么目录。如果你想坚持, 持久性代码:使用常规文件,而不是临时文件。你知道吗
相关问题 更多 >
编程相关推荐