首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python:从multiprocessing.Process中写入全局文本文件

Python:从multiprocessing.Process中写入全局文本文件
EN

Stack Overflow用户
提问于 2018-07-06 04:43:35
回答 1查看 255关注 0票数 1

我想启动一个可以写入文本文件的mp.Process。但是我发现在脚本的末尾,写入文件的数据实际上并没有保存到磁盘。我不知道发生了什么。下面是一个最小的工作示例:

代码语言:javascript
复制
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()

有没有人有建议?上下文是这个进程最终将侦听传入的数据,因此它确实需要独立于脚本中发生的其他事情运行。

EN

回答 1

Stack Overflow用户

发布于 2018-07-06 04:57:01

问题是您是在主进程中打开该文件。打开的文件不会传递给子进程,因此您需要在函数中打开它。

此外,函数外部的每个代码都为每个进程执行一次,因此您会多次覆盖该文件。

代码语言:javascript
复制
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不允许多个进程同时打开一个文件。最好的解决方案是使用队列,并将数据传递给主进程,然后主进程将数据写入文件。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51199599

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档