【问题标题】:Not able to write into a file using Python multiprocessing无法使用 Python 多处理写入文件
【发布时间】:2015-02-04 16:26:22
【问题描述】:
from itertools import product

f = open('filename.txt', 'a')

def worker(i, j):
    print i,j
    f.write("%s\t%s\n"%(i,j))
    return

def main():
    a_list = ['1', '2', '3', '4', '5'] #5 item
    b_list = ['6', '7', '8'] #3 item
    # Total 5*3=15 combinations

    from multiprocessing import Pool
    pool = Pool(processes=4)
    results = [pool.apply_async(worker, args=(i, j)) for i, j in product(a_list, b_list)]
    output = [p.get() for p in results]

main()
f.close()

这是我试图运行并将结果存储在 txt 文件中的代码,但我无法找出为什么它不写,尽管它在终端中打印。任何帮助将不胜感激。

【问题讨论】:

  • 这是linux还是windows?脚本终止后内容是否出现在文件中?
  • 它的 linux(ubuntu)。完成此程序后,我得到空白文件。

标签: python python-2.7 multiprocessing python-multiprocessing


【解决方案1】:

f.write(...) 语句之后添加f.flush()

【讨论】:

  • 谢谢!你能解释一下这个问题吗,因为我从来没有遇到过这种情况。
  • @michael 我相信原因是,因为文件对象没有在您的工作进程中打开,所以当工作人员退出时它不会自动刷新/关闭。因此,您的写入实际上从未写入文件,它只是写入工作人员本地的缓冲区,然后在进程退出时丢失。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
  • 2013-03-09
  • 1970-01-01
  • 2017-08-22
  • 1970-01-01
  • 2022-07-06
  • 2014-12-23
相关资源
最近更新 更多