使用队列写入同一文件的Python多处理
我知道有许多关于将多处理结果写入单个文件的栈上交换帖子,我在阅读了这些帖子之后开发了我的代码。我试图实现的是并行运行“RevMapCoord”函数,并使用multiprocess.queue将其结果写入一个文件中。但我在排队工作时遇到了问题。我的代码:使用队列写入同一文件的Python多处理,python,file-io,queue,multiprocessing,Python,File Io,Queue,Multiprocessing,我知道有许多关于将多处理结果写入单个文件的栈上交换帖子,我在阅读了这些帖子之后开发了我的代码。我试图实现的是并行运行“RevMapCoord”函数,并使用multiprocess.queue将其结果写入一个文件中。但我在排队工作时遇到了问题。我的代码: def RevMapCoord(list): "Read a file, Find String and Do something" def feed(queue, parlist): for par in parlist:
def RevMapCoord(list):
"Read a file, Find String and Do something"
def feed(queue, parlist):
for par in parlist:
print ('Echo from Feeder: %s' % (par))
queue.put(par)
print ('**Feeder finished queing**')
def calc(queueIn, queueOut):
print ('Worker function started')
while True:
try:
par = queueIn.get(block = False)
res = RevMapCoord(final_res)
queueOut.put((par,res))
except:
break
def write(queue, fname):
fhandle = open(fname, "w")
while True:
try:
par, res = queue.get(block = False)
print >>fhandle, par, res
except:
break
fhandle.close()
feedProc = Process(target = feed , args = (workerQueue, final_res))
calcProc = [Process(target = calc , args = (workerQueue, writerQueue)) for i in range(nproc)]
writProc = Process(target = write, args = (writerQueue, sco_inp_extend_geno))
feedProc.start()
print ('Feeder is joining')
feedProc.join ()
for p in calcProc:
p.start()
for p in calcProc:
p.join()
writProc.start()
writProc.join ()
当我运行此代码脚本时,会在“feedProc.start()”步骤中出错。屏幕的最后几行输出显示“feedProc.start()”末尾的打印语句:
但在执行下一行“feedProc.join()”之前挂起。代码不出错,继续运行,但不执行任何操作(挂起)。请告诉我我犯了什么错误。我认为你应该把你的例子精简到最基本的部分。例如:
from multiprocessing import Process, Queue
def f(q):
q.put('Hello')
q.put('Bye')
q.put(None)
if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
with open('file.txt', 'w') as fp:
while True:
item = q.get()
print(item)
if item is None:
break
fp.write(item)
p.join()
这里我有两个进程(主进程,p)。p将字符串放入由主进程检索的队列中。当主进程找不到(我用来表示“我完成了”的哨兵)时,它就会中断循环
将其扩展到多个进程(或线程)是很简单的。我通过在Python3中使用“map\u async”函数,将多进程的结果写入单个文件。下面是我编写的函数:
def PPResults(module,alist):##Parallel processing
npool = Pool(int(nproc))
res = npool.map_async(module, alist)
results = (res.get())###results returned in form of a list
return results
因此,我为这个函数提供了一个“a_list”中的参数列表,“module”是一个进行处理并返回结果的函数。上面的函数继续以列表的形式收集结果,并在处理完“a_list”中的所有参数后返回。结果的顺序可能不正确,但顺序并不重要对我来说,这很好。可以迭代“结果”列表,并将单个结果写入文件,如:
fh_out = open('./TestResults', 'w')
for i in results:##Write Results from list to file
fh_out.write(i)
为了保持结果的顺序,我们可能需要使用类似于我在问题(上面)中提到的“队列”。虽然我能够修复代码,但我相信这里不需要提到它
谢谢
AK您应该尝试运行您的示例(它给出了一个错误)。您不能以这种方式将多个项目放在队列中。实际上,您只在列表中放置了一个项目。
TypeError:需要一个字符缓冲区对象。
i've err:|@b1-新的(并且正确,谢谢Gerrat)版本适用于python 2.7.5和3.2.3。试试看!
fh_out = open('./TestResults', 'w')
for i in results:##Write Results from list to file
fh_out.write(i)