【问题标题】:Python multiprocessing program not running to the endPython多处理程序没有运行到最后
【发布时间】:2014-02-13 08:46:18
【问题描述】:

我是 python 多处理的新手。

基本上我的问题场景是我想在一组表上并行运行我的 python 脚本,比如 2 个表。

这里我的 python 脚本从每个表中并行读取数据,然后将每个表中的数据写入另一个表中。

我编写了以下代码 sn-p 来创建多进程 python 脚本。但是,当我运行脚本时,它没有完成,也没有抛出任何错误消息。

count = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=count)
args = [ ('yelp','localhost:9160','cassa1','flight88'), ('yelp','localhost:9160','cassa1','flight96') ]
for a in args:
    print a
    pool.apply_async(user_input,a)

感谢您对此的帮助,因为我很困惑并被困在这里。

【问题讨论】:

  • 你知道user_input中的处理是否开始了吗?

标签: python python-2.7 parallel-processing multiprocessing python-multithreading


【解决方案1】:

您的脚本在子进程完成其任务之前退出。在末尾添加:

pool.close() # no more tasks
pool.join()  # wait for the remaining tasks to complete

另外,您可以改用pool.imap*() 方法:

from multiprocessing import Pool

def safe_user_input(args):
    try:
         return user_input(*args), None
    except Exception as e:
         return None, str(e)

if __name__=="__main__":       
   tables = [
        ('yelp','localhost:9160','cassa1','flight88'),
        ('yelp','localhost:9160','cassa1','flight96')
   ]

   pool = Pool() # use all available CPUs
   for result, error in pool.imap_unordered(safe_user_input, tables):
       if error is None: # no error
          print(result)

【讨论】:

    猜你喜欢
    • 2015-04-28
    • 2017-05-29
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多