如何对列表中的循环进行多处理

时间:2017-06-26 06:26:22

标签: python multithreading multiprocessing

我有一个可以通过使用python轻松实现的任务,但是我的脚本完成需要很长时间。所以我想把它改成一个多处理脚本。我不知道怎么样,我试图使用threading,但似乎并不适合这种情况。

我需要获取所有页面'将URL放入名为page_list的列表中,然后获取这些页面的内容并使用BeautifulSoup获取某些类型的内容。 这就是我所拥有的:

some_list_from_page_content_1=[]
some_list_from_page_content_2=[]
class sth():
        def get_rv_content(self,somevar_from_another_method):
                ...
                page_list=[page1,page2,page3,page4....]
                for i in range(len(page_list)):
                        Page_Content=session.get(page_list[i],headers=req_header).content
                some_list_from_page_content_1=[x for x in Page_Content if foo]+some_list_from_page_content_1
                some_list_from_page_content_2=[x for x in Page_Content if foo]+some_list_from_page_content_2

1 个答案:

答案 0 :(得分:0)

尝试使用dask并行化。

基本上,使用dask.delayeddask.compute可以实现并行地图功能。 例如:

从dask导入延迟,计算 从时间导入睡眠

def fun(x):
    sleep(x)
    return x

ls = range(10)
res = [delayed(sleep)(x) for x in ls]
print res

将以纳秒为单位打印延迟列表:

[Delayed('fun-790acf2b-873d-4fd8-be07-2bc8111c4e01'), Delayed('fun-3c8c0c8e-699e-4029-ad12-8b5daefe13ad'), Delayed('fun-9da2e125-1910-4761-b1ad-23efa5f31096'), Delayed('fun-19a15dd5-5e4d-4103-8099-f3457b3cfc3a'), Delayed('fun-56d55b5e-8bb3-4ad9-8d7f-50a6509832b6'), Delayed('fun-d7efe939-7828-4d04-9c1c-60421983141f'), Delayed('fun-044ce640-7537-477e-bff8-9b0c92e62a7a'), Delayed('fun-5b833609-a268-4ef5-a8f1-acb4be4079d8'), Delayed('fun-f33e179e-7466-4763-ab08-ab735dccd8a8'), Delayed('fun-56b5eb76-85d4-4f03-8805-eeb891a14d0d')]

然后使用compute实际上会执行该功能(瘫痪):

print compute(res)

将打印结果(更快):

([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],)

注意 - 要获得结果list,请查找compute(res)[0]

因此,在你的情况下 - 只需用for循环替换for循环中的函数的执行,然后在最终结果上运行compute。

请注意,您可能需要运行计算元素:

print [compute(r) for r in res]    
[(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,)]