我如何跟踪一大批任务的进度?

2024-03-29 09:54:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有时会通过Python的grequest.map函数发送大量请求。目前我的代码如下所示

# passes these two into the function. The list of parameters can sometimes be thousands long.
# made this example up
local_path = 'https://www.google.com/search?q={}'
parameters = [('the+answer+to+life+the+universe+and+everything'), ('askew'), ('fun+facts')]
    s = requests.Session()
    retries = Retry(total=5, backoff_factor=0.2, status_forcelist=[500,502,503,504], raise_on_redirect=True, raise_on_status=True)
    s.mount('http://', HTTPAdapter(max_retries=retries))
    s.mount('https://', HTTPAdapter(max_retries=retries))
    async_list = []
    for parameters in parameter_list:
        URL = local_path.format(*parameters)
        async_list.append(grequests.get(URL, session=s))
    results = grequests.map(async_list)

我是tqdm库的粉丝,希望能有一个进度指标来显示有多少请求已经完成,还有多少请求仍在等待,但我不确定是否可以从grequest.getSession轮询或生成一个钩子。我确实尝试过使用grequests.get(URL, hooks={'response': test}, session=s),但这似乎实际上是将响应本身输入到测试函数中,然后results就有了None的内容。你知道吗

编辑:在我发布这个问题后不久,我研究了test钩子函数的返回值,但是无论我尝试什么,似乎如果有钩子,map函数在有响应之前不会阻塞;结果是None响应,我的钩子也没有任何响应。你知道吗

如何跟踪大量请求的进度?你知道吗


Tags: thepath函数httpsurlmapgetasync
1条回答
网友
1楼 · 发布于 2024-03-29 09:54:18

使用hooks参数是正确的解决方案。我发现我设置的test回调遇到了一个异常(诅咒那些微小的作用域错误),由于我没有为请求设置异常处理程序,它导致了一个静默错误,导致None响应。你知道吗

这就是我最后的设置。你知道吗

track_requests = None
def request_fulfilled(r, *args, **kwargs):
    track_requests.update()

local_path = 'https://www.google.com/search?q={}'
parameters = [('the+answer+to+life+the+universe+and+everything'), ('askew'), ('fun+facts')]
    global track_requests # missing this line was the cause of my issue...
    s = requests.Session()
    s.hooks['response'].append(request_fulfilled) # assign hook here
    retries = Retry(total=5, backoff_factor=0.2, status_forcelist=[500,502,503,504], raise_on_redirect=True, raise_on_status=True)
    s.mount('http://', HTTPAdapter(max_retries=retries))
    s.mount('https://', HTTPAdapter(max_retries=retries))
    async_list = []
    for parameters in parameter_list:
        URL = local_path.format(*parameters)
        async_list.append(grequests.get(URL, session=s))
    track_requests = tqdm(total=len(async_list))
    results = grequests.map(async_list)
    track_requests.close()
    track_requests = None

相关问题 更多 >