简体   繁体   English

requests.get 在 multiprocessing.Pool 中调用时挂起

[英]requests.get hangs when called in a multiprocessing.Pool

I have the following code:我有以下代码:

def process_url(url):
    print '111'
    r = requests.get(url)
    print '222' # <-- never even gets here
    return


urls_to_download = [list_or_urls]
PARALLEL_WORKERS = 4

pool = Pool(PARALLEL_WORKERS)
pool.map_async(process_url, urls_to_download)
pool.close()
pool.join()

Every time I do this, it runs the first four items and then just hangs.每次我这样做时,它都会运行前四个项目,然后就挂起。 I don't think it's a timeout issue, as it is extremely fast to download the four urls.我认为这不是超时问题,因为下载四个网址非常快。 It is just after fetching those first four it hangs indefinitely.只是在获取前四个之后,它就会无限期地挂起。

What do I need to do to remedy this?我需要做什么来解决这个问题?

The problem问题

Even though this question uses python 2, you can still reproduce this "error" in python 3. This is happening because pool.async_map returns an object of class AsyncResult .即使这个问题使用了 python 2,你仍然可以在 python 3 中重现这个“错误”。这是因为pool.async_map返回一个AsyncResult类的对象。 To receive the result (or traceback in case of error) of the async_map call, you need to use get() .要接收async_map调用的结果(或出现错误时的回溯),您需要使用get() Joining the pool will not work here since the job has already been completed, with the result being an AsyncResult which acts similar to a Promise.由于作业已经完成,因此在此处加入池将不起作用,结果是类似于 Promise 的AsyncResult

So, what's the solution?那么,解决方案是什么?

Simply, add a call to wait for the result to be received:只需添加一个调用以等待接收结果:

from multiprocessing import Pool
import requests

def process_url(url):
    print('111')
    r = requests.get(url)
    print('222') # <-- never even gets here (not anymore!)
    return


if __name__ == "__main__":
    urls_to_download = ['https://google.com'] * 4
    PARALLEL_WORKERS = 4

    pool = Pool(PARALLEL_WORKERS)
    a = pool.map_async(process_url, urls_to_download)
    
    # Add call here
    a.get()

    pool.close()
    pool.join()

Output输出

111
111
111
111
222
222
222
222

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM