为子进程写入文件输入
Write file input for subprocess
我需要在以文本文件作为输入的循环中调用例程。因为我不想一直打开和关闭文本文件,所以我在循环中保持打开状态。例如:
with open("test.txt",'r+') as w_file:
w_file.write(str(0.8) + "\n" + str(0.2))
subprocess.call(["cat","test.txt"]) #Here I want to call my routine
但文件仍处于旧状态。为什么?处理这个问题的最佳方法是什么?
您需要在写入后关闭文件。
尝试:
with open("test.txt",'r+') as w_file:
w_file.write(str(0.8) + "\n" + str(0.2))
subprocess.call(["cat","test.txt"]) #Here I want to call my routine
或者不关闭,刷新文件
with open("test.txt",'r+') as w_file:
w_file.write(str(0.8) + "\n" + str(0.2))
w_file.flush()
subprocess.call(["cat","test.txt"]) #Here I want to call my routine
这应该有效:
with open("test.txt",'r+') as w_file:
w_file.write(str(0.8) + "\n" + str(0.2))
w_file.flush()
subprocess.call(["cat","test.txt"])
方法 "flush" 将类文件对象 w_file 引用的实际文件与仍在内存中的内容同步,因此当您通过文件名引用文件时(而不是 w_file FLO),您会看到最新版本。
我需要在以文本文件作为输入的循环中调用例程。因为我不想一直打开和关闭文本文件,所以我在循环中保持打开状态。例如:
with open("test.txt",'r+') as w_file:
w_file.write(str(0.8) + "\n" + str(0.2))
subprocess.call(["cat","test.txt"]) #Here I want to call my routine
但文件仍处于旧状态。为什么?处理这个问题的最佳方法是什么?
您需要在写入后关闭文件。 尝试:
with open("test.txt",'r+') as w_file:
w_file.write(str(0.8) + "\n" + str(0.2))
subprocess.call(["cat","test.txt"]) #Here I want to call my routine
或者不关闭,刷新文件
with open("test.txt",'r+') as w_file:
w_file.write(str(0.8) + "\n" + str(0.2))
w_file.flush()
subprocess.call(["cat","test.txt"]) #Here I want to call my routine
这应该有效:
with open("test.txt",'r+') as w_file:
w_file.write(str(0.8) + "\n" + str(0.2))
w_file.flush()
subprocess.call(["cat","test.txt"])
方法 "flush" 将类文件对象 w_file 引用的实际文件与仍在内存中的内容同步,因此当您通过文件名引用文件时(而不是 w_file FLO),您会看到最新版本。