Python 如何将错误记录到文件中,并且不会因异常而失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3383865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to log error to file, and not fail on exception
提问by Blankman
I am downloading a file from the net, and it fails even though I am doing:
我正在从网上下载一个文件,即使我在做,它也失败了:
for p in query:
对于查询中的 p:
try:
except IOError as e:
print e;
If there is an error, I want to log it, and then continue on with the next file.
如果有错误,我想记录它,然后继续处理下一个文件。
In this loop, I am trying to download an image, if for some reason the filename was bad, or the website was down, etc., I want to continue with the next item in the for loop.
在这个循环中,我试图下载一个图像,如果由于某种原因文件名不好,或者网站关闭等,我想继续 for 循环中的下一个项目。
Is there a more generic error that won't fail and continue processing?
是否有更通用的错误不会失败并继续处理?
Also, how can I log errors to a file?
另外,如何将错误记录到文件中?
采纳答案by Jeet
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:
正如 Lott 所指出的,如果下载失败,除非问题在上游(或您的下载地址)得到解决,否则您能做的最好的事情就是重试。但是,如果情况是您有一个下载列表,并且只想跳过失败的下载而不是退出,那么:
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
Things to note:
注意事项:
(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.
(1) 使用logging~unutbu 建议的 " " 模块,为您的日志输出提供更大的灵活性和功能,包括时间戳,根据错误级别同时写入不同的通道(例如,stderr、文件)等。 等等。
(2) You might consider implementing the above logic using the "with" construct.
(2) 您可以考虑使用 " with" 构造来实现上述逻辑。
回答by unutbu
You could use the logging module:
您可以使用日志记录模块:
import logging
logging.basicConfig(filename='/tmp/myapp.log', level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(name)s %(message)s')
logger=logging.getLogger(__name__)
try:
1/0
except ZeroDivisionError as err:
logger.error(err)
Running the script writes in /tmp/myapp.log:
运行脚本在 /tmp/myapp.log 中写入:
% cat /tmp/myapp.log
2010-08-01 17:50:45,960 ERROR __main__ integer division or modulo by zero
回答by nate c
This catches everything. But it is much, much better to catch the exact exception. python <= 2.7
这抓住了一切。但是捕获确切的异常要好得多。蟒蛇<= 2.7
while True:
try:
doStuff()
except Exception, e:
f = open('log.txt', 'w')
f.write('An exceptional thing happed - %s' % e)
f.close()
回答by Avinav Mishra
This will write your error to a log file and continue to run the code.
这会将您的错误写入日志文件并继续运行代码。
import traceback
#This line opens a log file
log = open("log.txt", "w")
try:
# some code
# Below line will print any print to log file as well.
print("Creating DB Connection", file = log)
except Exception:
traceback.print_exc(file=log)
continue

