我想启动一个可以写入文本文件的mp.Process。但是我发现在脚本的末尾,写入文件的数据实际上并没有保存到磁盘。我不知道发生了什么。下面是一个最小的工作示例:
import os, time, multiprocessing
myfile = open("test.dat", "w")
def main():
proc = multiprocessing.Process(target=writer)
proc.start()
time.sleep(1)
print "Times up! Closing file..."
myfile.flush()
os.fsync(myfile.fileno())
print "Closing %s" % (myfile)
myfile.close()
print "File closed. Have a nice day!"
print "> cat test.dat"
def writer():
data = "0000"
for _ in xrange(5):
print "Writing %s to %s" % (data, myfile)
myfile.write(str(data) + '\n')
# if you comment me, writing to disk works!
# myfile.flush()
# os.fsync(myfile.fileno())
if __name__ == "__main__":
main()
有没有人有建议?上下文是这个进程最终将侦听传入的数据,因此它确实需要独立于脚本中发生的其他事情运行。
发布于 2018-07-06 04:57:01
问题是您是在主进程中打开该文件。打开的文件不会传递给子进程,因此您需要在函数中打开它。
此外,函数外部的每个代码都为每个进程执行一次,因此您会多次覆盖该文件。
def main():
# create the file empty so it can be appended to
open("test.dat", "w").close()
proc = multiprocessing.Process(target=writer)
proc.start()
def writer():
with open('test.dat', 'a') as myfile: # opens the file for appending
...
myfile.write(...)
...
现在,一些OSes不允许多个进程同时打开一个文件。最好的解决方案是使用队列,并将数据传递给主进程,然后主进程将数据写入文件。
https://stackoverflow.com/questions/51199599
复制相似问题