如何检查使用请求模块的程序是否已死

how to check whether a program using requests module is dead or not

我正在尝试使用 python 下载一批文件,并且我使用打开流的请求模块,换句话说,我以 200K 块的形式检索每个文件。 但是,有时,下载可能会因为卡住(无响应)并且没有错误而停止。我猜这是因为我的电脑和服务器之间的连接不够稳定。这是我的问题,如何检查这种停止并建立新连接?

你可能不想从外部检测到这个,当你可以使用timeoutsrequests失败而不是停止时服务器停止发送字节。

由于您没有向我们展示您的代码,因此很难向您展示如何更改它……但我将向您展示如何更改其他代码:

# hanging
text = requests.get(url).text

# not hanging
try:
    text = requests.get(url, timeout=10.0).text
except requests.exceptions.Timeout:
    # failed, do something else

# trying until success
while True:
    try:
        text = requests.get(url, timeout=10.0).text
        break
    except requests.exceptions.Timeout:
        pass

如果你出于某种原因想从外部检测它,你需要使用multiprocessing或类似的方法来移动requests-驱动代码到子进程。理想情况下,您希望它 post 更新某些 Queue 或设置并通知某些 Condition 受保护的共享标志变量每 200KB,然后主进程可以阻塞 QueueConditionkill 子进程超时。例如(伪代码):

def _download(url, q):
    create request
    for each 200kb block downloaded:
        q.post(buf)

def download(url):
    q = multiprocessing.Queue()
    with multiprocessing.Process(_download, args=(url, q)) as proc:
        try:
            return ''.join(iter(functools.partial(q.get, timeout=10.0)))
        except multiprocessing.Empty:
            proc.kill()
            # failed, do something else