且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将错误记录到文件,并且不会因异常而失败

更新时间:2021-08-16 23:18:34

如Lott所指出,如果下载失败,除非该问题已在上游解决(或使用您的下载地址),则您***的办法是再试一次.但是,如果情况是您具有下载列表,并且只想跳过失败的下载而不是退出,则:

As pointed out by Lott, if a download is failing, unless the problem is fixed upstream (or with your download address), the best you can do is to try again. However, if the situation is that you have a list of downloads, and simply want to skip over failed downloads instead of exiting, then:

logf = open("download.log", "w")
for download in download_list:
    try:
        # code to process download here
    except Exception as e:     # most generic exception you can catch
        logf.write("Failed to download {0}: {1}\n".format(str(download), str(e)))
        # optional: delete local version of failed download
    finally:
        # optional clean up code
        pass

注意事项:

(1)〜unutbu建议使用"logging"模块,可为您的日志输出(包括时间戳)提供更大的灵活性和功能,同时写入不同的通道(例如,stderr,文件)取决于错误级别等.

(1) Use of the "logging" module, as suggested by ~unutbu, gives you much more flexibility and power with your logging output, including time stamp, simultaneously writing to different channels (e.g., stderr, file) depending on error levels, etc. etc.

(2)您可以考虑使用"with"构造实现上述逻辑.

(2) You might consider implementing the above logic using the "with" construct.