【问题标题】:multiprocessing function call多处理函数调用
【发布时间】:2016-10-04 19:46:41
【问题描述】:

我正在尝试在 Python 中进行一些多处理。我有一个函数做一些工作并返回一个列表。我想在几个案例中重复这一点。最后,我想获取每个并行调用的返回列表并将它们统一(只有一个列表,删除了所有重复项)。

def get_version_list(env):
    list = []
    #do some intensive work
    return list

from multiprocessing import Pool

pool = Pool()

result1 = pool.apply_async(get_version_list, ['prod'])
result2 = pool.apply_async(get_version_list, ['uat'])
#etc, I have six environment to check.

alist = result1.get()
blist = result2.get()

这不起作用(不确定函数调用语法,但我也尝试了其他方法,但没有成功),它给了我一个错误(并且重复了很多,因为我的密集工作正在进行大约 300 个 request.post 调用)。

运行时错误: 尝试在当前进程之前启动一个新进程 已完成引导阶段。

This probably means that you are on Windows and you have
forgotten to use the proper idiom in the main module:

    if __name__ == '__main__':
        freeze_support()
        ...

The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce a Windows executable.

【问题讨论】:

  • 错误信息的哪一部分不清楚?
  • 我猜我没看错……也许我该回家了。
  • 对不起,如果我的评论听起来很刺耳。了解多处理在 Windows 上的工作原理很重要。每个进程都会导入主脚本——它通常也包含主进程。这就是为什么将它与if __name__ == '__main__': 分开很重要的原因(因此主要部分不会在每次发生时都重新执行)。
  • 我明白了,我只是累了,没有注意。这是一个没有结构的小型测试脚本,我想在将代码集成到 Web 服务器之前对其进行测试(使用 web.py 完成)。

标签: python multiprocessing


【解决方案1】:

您必须将多处理部分放在主函数中,例如:

def get_version_list(env):
    list = []
    print "ENV: " + env
    return list


if __name__ == '__main__':
    from multiprocessing import Pool

    pool = Pool()

    result1 = pool.apply_async(get_version_list, ['prod'])
    result2 = pool.apply_async(get_version_list, ['uat'])
    #etc, I have six environment to check.

    alist = result1.get()
    blist = result2.get()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    相关资源
    最近更新 更多