Not able to write into a file using Python multiprocessing

烈酒焚心 提交于 2019-12-10 12:07:17

问题


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()

this is the code I'm trying to run and store result in a txt file but I'm unable to findout why this isn't writing, although its printing in terminal. any help would be appreciated.


回答1:


add f.flush() after the f.write(...) statement



来源:https://stackoverflow.com/questions/28326378/not-able-to-write-into-a-file-using-python-multiprocessing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!