使用队列写入同一fi的Python多处理

2024-05-08 16:50:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道有很多关于堆栈交换的帖子,都是关于将多处理的结果写入单个文件的,我只在阅读了这些帖子之后就开发了我的代码。我试图实现的是并行运行'RevMapCoord'函数,并使用multiprocess.queue将其结果写入一个文件。但我在排队工作时遇到了问题。我的代码:

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()”结尾的print语句:

Echo from Feeder: >AK779,AT61680,50948-50968,50959,6,0.406808,Ashley,Dayne
Echo from Feeder: >AK832,AT30210,1091-1111,1102,7,0.178616,John,Caine
**Feeder finished queing**

但在执行下一行“feedProc.join()”之前挂起。代码没有错误,继续运行但什么也不做(挂起)。请告诉我我犯了什么错误。


Tags: 代码infromechoforqueuedefres
2条回答

我认为你应该把你的例子精简到最基本的程度。例如:

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_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'是一个执行处理并返回结果的函数。上面的函数继续以list的形式收集结果,并在处理完'a_list'中的所有参数后返回。结果可能不是正确的顺序,但由于顺序对我来说并不重要,所以效果很好。“结果”列表可以迭代,单个结果可以写入如下文件:

fh_out = open('./TestResults', 'w')
for i in results:##Write Results from list to file
    fh_out.write(i)

为了保持结果的顺序,我们可能需要使用类似于我在上面的问题中提到的“队列”。虽然我可以修复代码,但我相信这里不需要提到它。

谢谢

AK公司

相关问题 更多 >