多处理函数调用
问题描述:
我想在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调用)。
RuntimeError: 尝试在当前进程 完成引导阶段之前开始新进程。
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.
答
你必须把多部分的主要功能内,如:
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()
+0
是的,解决了错误信息 – Amaranth
哪一部分的错误消息不清楚? – martineau
我想我没有正确阅读......也许是时候让我回家了。 – Amaranth
对不起,如果我的评论听起来刺耳。了解Windows上的多处理功能很重要。每个进程导入主脚本 - 通常也包含主进程。这就是为什么用'if __name__ =='__main __':'分隔它很重要(所以每次发生时都不重新执行主要部分)。 – martineau