首页 > 解决方案 > 在 Python 中使用 Pebble 重新启动/重建超时进程?

问题描述

我正在使用并发期货使用 API 从远程服务器下载报告。为了通知我报告已正确下载,我只需让函数打印出它的 ID。

我有一个问题,报告下载很少会无限期挂起。我没有收到超时错误或连接重置错误,只是在那里挂了几个小时,直到我终止整个过程。这是 API 的一个已知问题,没有已知的解决方法。

我做了一些研究并转而使用基于Pebble的方法来实现函数超时。我的目标是记录下载失败的报告的 ID 并重新开始。

不幸的是,因为我不知道如何真正检索我未能下载的报告的 ID,所以我遇到了一些难题。我正在使用与答案类似的布局:

from pebble import ProcessPool
from concurrent.futures import TimeoutError

def sometimes_stalling_download_function(report_id):
    ...
    return report_id

with ProcessPool() as pool:
    future = pool.map(sometimes_stalling_download_function, report_id_list, timeout=10)

    iterator = future.result()

    while True:
        try:
            result = next(iterator)
        except StopIteration:
            break
        except TimeoutError as error:
            print("function took longer than %d seconds" % error.args[1])
            #Retrieve report ID here
            failed_accounts.append(result)

我想要做的是在超时的情况下检索报告 ID,但似乎无法从该异常中访问它。在超时异常的情况下是否可以让函数输出 ID,或者我是否必须重新考虑如何完全下载报告?

标签: pythonconcurrencyconcurrent.futures

解决方案


map 函数返回一个future对象,该对象按照提交的顺序生成结果。

因此,要了解report_id导致超时的原因,您只需检查其在report_id_list.

index = 0

while True:
    try:
        result = next(iterator)
    except StopIteration:
        break
    except TimeoutError as error:
        print("function took longer than %d seconds" % error.args[1])
        #Retrieve report ID here
        failed_accounts.append(report_id_list[index])
    finally:
        index += 1

推荐阅读