如何在Python 3中打印异常?

Hao*_*hen 45 python exception web-scraping python-3.x

现在,我在except Exception:条款中捕获了异常,并且做了print(exception).结果不提供任何信息,因为它始终打印<class 'Exception'>.我知道这曾经在python 2中工作,但我如何在python3中做到这一点?

Noa*_*art 77

我猜你需要将Exception变量分配给变量.如Python 3教程中所示:

def fails():
    x = 1 / 0

try:
    fails()
except Exception as ex:
    print(ex)
Run Code Online (Sandbox Code Playgroud)

简要说明as是在某些复合语句中使用的伪赋值关键字,用于将前一个语句赋值给变量或将其别名.

在这种情况下,as将捕获的异常分配给变量,以允许稍后存储和使用的有关异常的信息,而不是需要立即处理.(这在Python 3语言参考:try声明中有详细讨论.)


使用的另一个复合语句aswith声明:

@contextmanager
def opening(filename):
    f = open(filename)
    try:
        yield f
    finally:
        f.close()

with opening(filename) as f:
    # ...read data from f...
Run Code Online (Sandbox Code Playgroud)

这里,with语句用于使用上下文管理器定义的方法包装块的执行.它的功能类似于try...except...finally整齐的生成器包中的扩展语句,并且as语句将生成器生成的结果从上下文管理器分配给变量以供扩展使用.(这在Python 3语言参考:with声明中有详细讨论.)


最后,as可以在导入模块时使用,将模块别名为不同的(通常更短的)名称:

import foo.bar.baz as fbb
Run Code Online (Sandbox Code Playgroud)

这在Python 3语言参考:import声明中有详细讨论.


rig*_*gel 26

这些是自python 2以来的变化:

    try:
        1 / 0
    except Exception as e: # (as opposed to except Exception, e:)
                           # ^ that will just look for two classes, Exception and e
        # for the repr
        print(repr(e))
        # for just the message, or str(e), since print calls str under the hood
        print(e)
        # the arguments that the exception has been called with. 
        # the first one is usually the message. (OSError is different, though)
        print(e.args)
Run Code Online (Sandbox Code Playgroud)

  • Python 3似乎没有`message`属性,而`str(e)`则将错误的位置和类型附加到消息中。正确? (3认同)
  • 也许晚了,但只是为了清除... str(e) 似乎只返回 python 3 中的消息,即:“名称‘re’未定义” (2认同)

wpe*_*rcy 9

尝试

except Exception as e:
    print(e)
Run Code Online (Sandbox Code Playgroud)


cao*_*aot 5

这是我喜欢的打印所有错误堆栈的方式。

import logging

try:
    1 / 0
except Exception as _e:
    # any one of the follows:
    # print(logging.traceback.format_exc())
    logging.error(logging.traceback.format_exc())
Run Code Online (Sandbox Code Playgroud)

输出如下所示:

ERROR:root:Traceback (most recent call last):
  File "/PATH-TO-YOUR/filename.py", line 4, in <module>
    1 / 0
ZeroDivisionError: division by zero
Run Code Online (Sandbox Code Playgroud)

LOGGING_FORMAT

LOGGING_FORMAT = '%(asctime)s\n  File "%(pathname)s", line %(lineno)d\n  %(levelname)s [%(message)s]'
Run Code Online (Sandbox Code Playgroud)