python – 打印异常

我正在编写一个捕获错误(或异常)的小脚本.但是当异常发生时,我希望获得所有信息,如Traceback,异常名称和异常消息.如果没有捕获到异常但是下面的代码不应该受到影响它也应该起作用(i.d应该出现错误,但脚本不会停止工作).
例如:在以下代码中将抛出异常.如果发生这种情况(并且只有它发生)我想做“清理”.

try:
    1 / 0
except Exception as e:
    # Printing the Exception like it would have been done if the exception hadn't been caught:
    # Traceback (most recent call last):
    #  File "<stdin>",line 1,in <module>
    # ZeroDivisionError: integer division or modulo by zero
    # With the traceback,the exception name and the exception message.

    # Doing some additional stuff.
    pass

我不打算使用记录器,因为脚本非常智能(不超过100行)并且它只会被我使用.

编辑:我正在使用python 2.x.

解决方法

您将要使用traceback模块:

import traceback
try:
    raise Exception('what')
except Exception:
    print(traceback.format_exc())

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...