python 在python中将异常保存到文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1718295/
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
save Exceptions to file in python
提问by Joschua
I want to save all following Exceptions in a file. The reason why I need this is because the IDLE for python 3.1.1 in Ubuntu raises an Exception at calltipps, but close to fast, that it isn't readble. Also I need this for testing. The best, would be if I just call a function which saves all Exception to a file. Thank you! ;)
我想将所有以下异常保存在一个文件中。我需要这个的原因是因为 Ubuntu 中 python 3.1.1 的 IDLE 在 calltipps 上引发了一个异常,但接近于快速,它不可读。我也需要这个来测试。最好的情况是,如果我只是调用一个将所有异常保存到文件的函数。谢谢!;)
// edit:
// 编辑:
i had looked first for a more general way! so that you do not have to place your whole code in a function or indentation. but now that worked wery well for me. although I would be still grateful, if you find a way!
我首先寻找更通用的方法!这样您就不必将整个代码放在函数或缩进中。但现在这对我来说效果很好。如果您找到方法,我仍然会感激不尽!
thanks!
谢谢!
回答by Ned Batchelder
If you have a convenient main()
function (whatever it's called), then you can use the logging module:
如果你有一个方便的main()
函数(不管它叫什么),那么你可以使用日志模块:
import logging
def main():
raise Exception("Hey!")
logging.basicConfig(level=logging.DEBUG, filename='/tmp/myapp.log')
try:
main()
except:
logging.exception("Oops:")
logging.exception
conveniently gets the current exception and puts the details in the log:
logging.exception
方便地获取当前异常并将详细信息放入日志中:
ERROR:root:Oops:
Traceback (most recent call last):
File "C:\foo\foo.py", line 9, in <module>
main()
File "C:\foo\foo.py", line 4, in main
raise Exception("Hey!")
Exception: Hey!