java 的 printStackTrace() 在 python 中等效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7901238/
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
java's printStackTrace() equivalent in python
提问by Mohamed Khamis
In python except block, I want to print the error message but I don't want the program to stop executing, I understand that I have to do something like this
在 python 中,除了块,我想打印错误消息但我不希望程序停止执行,我知道我必须做这样的事情
try:
1/0
except:
print errorMessage
In the except part, I am looking to put something like java's printStackTrace()
在除了部分,我想放一些像 java 的东西 printStackTrace()
回答by NPE
Take a look at traceback.print_exc()
and the rest of the traceback
module.
看看模块traceback.print_exc()
的其余部分traceback
。
import traceback
try:
1/0
except:
print '>>> traceback <<<'
traceback.print_exc()
print '>>> end of traceback <<<'
There are some more examples towards the end of the traceback
documentation page.
在traceback
文档页面的末尾还有一些示例。
回答by MrColes
If you really just want the error message, you can just print the error (notice how I specify the exception in the except—that's good practice, see pep8for recommendations on catching errors):
如果你真的只想要错误消息,你可以只打印错误(注意我如何在 except 中指定异常——这是很好的做法,有关捕获错误的建议,请参阅pep8):
try:
1/0
except Exception as e:
print e
However, if you want the stackstrace, as @Eddified said in a comment, you can use the example in this answer. Or more specifically for your case:
但是,如果您想要 stackstrace,正如@Eddified 在评论中所说,您可以使用此答案中的示例。或者更具体地针对您的情况:
import traceback
try:
1/0
except Exception as e:
print e
traceback.print_stack()
回答by Xion
You can also use logging.exception
from the logging
module. It will print the current exception's stacktrace into the default logger as a message of severity ERROR
.
您也可以使用logging.exception
fromlogging
模块。它会将当前异常的堆栈跟踪作为严重性消息打印到默认记录器中ERROR
。
Link: http://docs.python.org/2/library/logging.html#logging.Logger.exception
链接:http: //docs.python.org/2/library/logging.html#logging.Logger.exception