繁体   English   中英

如何在 Python 中打印异常?

[英]How do I print an exception in Python?

如何在except:块中打印错误/异常?

try:
    ...
except:
    print(exception)

对于 Python 2.6 及更高版本以及 Python 3.x:

except Exception as e: print(e)

对于 Python 2.5 及更早版本,请使用:

except Exception,e: print str(e)

traceback模块提供了格式化和打印异常及其回溯的方法,例如,这将像默认处理程序一样打印异常:

import traceback

try:
    1/0
except Exception:
    traceback.print_exc()

输出:

Traceback (most recent call last):
  File "C:\scripts\divide_by_zero.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero

Python 2.6 或更高版本中,它更简洁:

except Exception as e: print(e)

在旧版本中,它仍然非常易读:

except Exception, e: print e

如果您想传递错误字符串,这里有一个来自错误和异常(Python 2.6) 的示例

>>> try:
...    raise Exception('spam', 'eggs')
... except Exception as inst:
...    print type(inst)     # the exception instance
...    print inst.args      # arguments stored in .args
...    print inst           # __str__ allows args to printed directly
...    x, y = inst          # __getitem__ allows args to be unpacked directly
...    print 'x =', x
...    print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

Python 3: logging

可以使用更灵活的logging模块来记录异常,而不是使用基本的print()函数。 logging模块提供了许多额外的功能,例如将消息记录到给定的日志文件中,记录带有时间戳的消息以及有关日志记录发生位置的附加信息。 (有关更多信息,请查看官方文档。)

可以使用模块级函数logging.exception()记录异常,如下所示:

import logging

try:
    1/0
except BaseException:
    logging.exception("An exception was thrown!")

输出:

ERROR:root:An exception was thrown!
Traceback (most recent call last):
  File ".../Desktop/test.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero 

笔记:

  • 函数logging.exception()只能从异常处理程序中调用

  • logging模块不应在日志处理程序中使用以避免RecursionError (感谢@PrakharPandey)


替代日志级别

也可以使用关键字参数exc_info=True来记录另一个日志级别的异常,如下所示:

logging.debug("An exception was thrown!", exc_info=True)
logging.info("An exception was thrown!", exc_info=True)
logging.warning("An exception was thrown!", exc_info=True)

(我打算将此作为对@jldupont 答案的评论,但我没有足够的声誉。)

我在其他地方也看到过类似@jldupont 的回答。 FWIW,我认为重要的是要注意这一点:

except Exception as e:
    print(e)

默认情况下会将错误输出打印到sys.stdout 一般来说,更合适的错误处理方法是:

except Exception as e:
    print(e, file=sys.stderr)

(请注意,您必须import sys才能使其工作。)这样,错误将打印到STDERR而不是STDOUT ,这允许正确的输出解析/重定向/等。 我知道这个问题严格来说是关于“打印错误”,但在这里指出最佳实践似乎很重要,而不是忽略这个可能导致最终不会更好地学习的人的非标准代码的细节。

我没有像 Cat Plus Plus 的回答那样使用traceback模块,也许这是最好的方法,但我想我会把它扔在那里。

在捕获异常时,人们几乎可以控制要显示/记录来自回溯的哪些信息。

编码

with open("not_existing_file.txt", 'r') as text:
    pass

将产生以下回溯:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

打印/记录完整的回溯

正如其他人已经提到的,您可以使用 traceback 模块捕获整个回溯:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()

这将产生以下输出:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

您可以通过使用日志记录来实现相同的目的:

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)

输出:

__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

仅打印/记录错误名称/消息

您可能对整个回溯不感兴趣,而只对最重要的信息(例如异常名称和异常消息)感兴趣,请使用:

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    print("Exception: {}".format(type(exception).__name__))
    print("Exception message: {}".format(exception))

输出:

Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'

在这里扩展“except Exception as e:”解决方案是一个不错的方法,其中包括一些附加信息,例如错误类型和发生位置。


try:
    1/0
except Exception as e:
    print(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}")

输出:

ZeroDivisionError at line 48 of /Users/.../script.py: division by zero

#尝试这个

try:

    print("Hare Krishna!")

except Exception as er:

    print(er)
    

如果您想要这样做,可以使用 assert 语句完成一个线性错误提升。 这将帮助您编写静态可修复的代码并及早检查错误。

assert type(A) is type(""), "requires a string"

我建议使用 try-except 语句。 此外,记录异常不是使用打印语句,而是在记录器上记录级别为 ERROR 的消息,我发现这比打印输出更有效。 该方法只能从异常处理程序中调用,如下所示:

import logging

try:
    *code goes here*
except BaseException:
    logging.exception("*Error goes here*")

如果您想了解有关日志记录和调试的更多信息,此 python 页面上有很好的文档。

使用as语句

try:
    # Code
except Exception as e:
    print(e)

如果要将消息打印到stderr,请以状态代码1(错误)退出:

import sys

try:
    ...
except Exception as e:
    sys.exit("Message to print to stderr")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM