无法使用 Python 多处理写入文件
Not able to write into a file using Python multiprocessing
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 文件中的代码,但我无法找出为什么它没有写入,尽管它在终端中打印。任何帮助将不胜感激。
在f.write(...)
语句后添加f.flush()
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 文件中的代码,但我无法找出为什么它没有写入,尽管它在终端中打印。任何帮助将不胜感激。
在f.write(...)
语句后添加f.flush()