我对多重处理完全陌生。我正在尝试更改我的代码以便同时运行部分代码。在
我有一个庞大的列表,其中我必须为每个节点调用一个API。因为API是独立的,所以我不需要第一个结果来继续第二个。所以,我有这个代码:
def xmlpart1(id):
..call the api..
..retrieve the xml..
..find the part of xml I want..
return xml_part1
def xmlpart2(id):
..call the api..
..retrieve the xml..
..find the part of xml I want..
return xml_part2
def main(index):
mylist = [[..,..],[..,..],[..,..],[..,...]] # A huge list of lists with ids I need for calling the APIs
myL= mylist[index] c
mydic = {}
for i in myL:
flag1 = xmlpart1(i)
flag2 = xmlpart2(i)
mydic[flag1] = flag2
root = "myfilename %s.json" %(str(index))
with open(root, "wb") as f:
json.dump(mydic,f)
from multiprocessing import Pool
if __name__=='__main__':
Pool().map(main, [0,1,2,3])
从这里和聊天中得到一些建议后,我得到了这个代码。问题仍然存在。我在9点50分运行脚本。10:25,第一个文件“myfilename 0.json”出现在我的文件夹中。现在是11点25分,其他文件都没有出现。子列表的长度相等,它们做同样的事情,所以它们需要的时间大致相同。在
这更适合
multiprocessing.Pool()
类。在下面是一个简单的例子:
其中:
inputs
是您的输入列表。每个输入被传递到作业并在单独的进程中处理。在当所有作业完成后,您将以列表形式返回结果。在
multiprocessing.Pool().map
就像Python内置的map()
,但它为您设置了一个worker进程池,并将每个输入传递给给定的函数。在有关详细信息,请参阅文档:http://docs.python.org/2/library/multiprocessing.html
相关问题 更多 >
编程相关推荐