如何在Python 3中打印异常?

时间:2017-01-11 17:13:48

标签: python python-3.x web-scraping

现在,我在except Exception:子句中捕获异常,然后执行print(exception)。结果不提供任何信息,因为它始终打印<class 'Exception'>。我知道这曾经在python 2中工作,但我怎么在python3中做呢?

7 个答案:

答案 0 :(得分:59)

我猜你需要将<link rel="stylesheet" href="https://path/to/bootstrap.css"> <link rel="stylesheet" href="https://path/to/main.css"> 分配给变量。正如shown in the Python 3 tutorial

Exception

为了简要说明,def fails(): x = 1 / 0 try: fails() except Exception as ex: print(ex) 是某些复合语句中使用的伪赋值关键字,用于将前一个语句赋值给变量或将其别名。

在这种情况下,as将捕获的异常分配给变量,允许稍后存储和使用的异常信息,而不是需要立即处理。 (这在Python 3 Language Reference: The try Statement中有详细讨论。)

使用as的其他复合语句是as语句:

with

这里,@contextmanager def opening(filename): f = open(filename) try: yield f finally: f.close() with opening(filename) as f: # ...read data from f... 语句用于使用context managers定义的方法包装块的执行。它的功能类似于整齐的生成器包中的扩展with语句,try...except...finally语句将生成器生成的结果从上下文管理器分配给变量以供扩展使用。 (这在Python 3 Language Reference: The with Statement中有详细讨论。)

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

as

Python 3 Language Reference: The import Statement

详细讨论了这一点

答案 1 :(得分:18)

这些是自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
    print(e) # for the repr
    print(str(e)) # for just the message
    print(e.args) # the arguments that the exception has been called with. 
                  # the first one is usually the message.

答案 2 :(得分:9)

尝试

except Exception as e:
    print(e)

答案 3 :(得分:1)

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

import logging

try:
    1 / 0
except Exception as _e:
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())

输出如下:

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

答案 4 :(得分:0)

我已经使用了这个:

except (socket.timeout, KeyboardInterrupt) as e:
    logging.debug("Exception : {}".format(str(e.__str__).split(" ")[3]))
    break

让我知道它是否对您不起作用!

答案 5 :(得分:0)

尽管如果您想要与 python2 python3 都兼容的代码,则可以使用以下代码:

import logging
try:
    1/0
except Exception as e:
    if hasattr(e, 'message'):
        logging.warning('python2')
        logging.error(e.message)
    else:
        logging.warning('python3')
        logging.error(e)

答案 6 :(得分:0)

[在Python3中]

假设您要处理IndexError并打印回溯,可以执行以下操作:

from traceback import print_tb 
empty_list = [] 
try: 
    x = empty_list[100]
except IndexError as index_error: 
    print_tb(index_error.__traceback__)

注意:您可以使用format_tb函数而不是print_tb来以字符串形式获取回溯,以进行记录。 希望这可以帮助。