python - 在 Python/Mechanize 中从 ECONNRESET 恢复

标签 python error-handling tcp mechanize

我有一个用 Python/Mechanize 编写的大型批量下载应用程序,旨在下载大约 20,000 个文件。显然,任何这么大的下载器偶尔都会遇到一些 ECONNRESET 错误。现在,我知道如何处理 each of these individually ,但是有两个问题:

  1. 我真的不想将每个出站网络调用都包装在 try/catch block 中。
  2. 即使我这样做了,一旦抛出异常,也很难知道如何处理错误。如果代码只是

    data = browser.response().read()
    

    然后我就知道如何处理它了,即:

    data = None
    while (data == None):
        try:
            data = browser.response().read()
        except IOError as e:
            if e.args[1].args[0].errno != errno.ECONNRESET:
                raise
            data = None
    

    但如果它只是一个随机实例

    browser.follow_link(link)
    

    如果 ECONNRESET 被扔在这里,我怎么知道 Mechanize 的内部状态是什么样的?例如,在再次尝试代码之前是否需要调用 browser.back()?从此类错误中恢复的正确方法是什么?

编辑:已接受答案中的解决方案当然有效,就我而言,实现起来并不难。然而,我在学术上仍然对是否存在可以导致更快地捕获错误的错误处理机制感兴趣。

最佳答案

也许将 try..except block 放在命令链的更高位置:

import collections
def download_file(url):
    # Bundle together the bunch of browser calls necessary to download one file.
    browser.follow_link(...)
    ...
    response=browser.response()
    data=response.read()

urls=collections.deque(urls)

while urls:
    url=urls.popleft()
    try:
        download_file(url)
    except IOError as err:
        if err.args[1].args[0].errno != errno.ECONNRESET:
            raise
        else:
            # if ECONNRESET error, add the url back to urls to try again later
            urls.append(url)

关于python - 在 Python/Mechanize 中从 ECONNRESET 恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4854809/

相关文章:

python - django objects.all() 与 objects.filter()

c - 在 C 中映射非顺序值的最佳方法

jquery - 从未调用过的jQuery Ajax错误函数

c++ - asio :how does server actively send information to client while listening to client at the same time?

c++ - Boost::asio::async_read() 缓冲区损坏问题

python - Sentry.io 动态忽略记录器

python - pandas 比较并从另一个数据框中选择最小的数字

python - 艰难地学习 Python,练习 35 : placing a regular expression

iphone - iPhone网络SSID

c - 接收多个 TCP 段