设为首页 收藏本站
查看: 1192|回复: 0

[经验分享] python中利用tracekback跟踪栈以及打印异常信息

[复制链接]

尚未签到

发表于 2017-5-7 14:01:01 | 显示全部楼层 |阅读模式
  ​##sys.exc_info()

返回 (type, value, traceback). type为异常类型, value为异常的参数(通常为异常错误的信息), traceback为跟踪回溯的对象.


    exc_type, exc_value, exc_traceback = sys.exc_info()
print "*** print sys.exc_info:"
print 'exc_type is: %s, exc_value is: %s, exc_traceback is: %s' % (exc_type, exc_value, exc_traceback)
  输出:


*** print sys.exc_info:
exc_type is: <type 'exceptions.IndexError'>, exc_value is: tuple index out of range, exc_traceback is: <traceback object at 0x7fee3b00eb48>

traceback.print_tb(traceback[, limit[, file]])
  打印栈的跟踪信息. 如果省略limit, 将打印所有跟踪入口信息. file默认为std.err.


    print "*** print_tb:"
traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
  输出:


*** print_tb:
File "t.py", line 13, in <module>
mock()

traceback.print_exception(type, value, traceback[, limit[, file]])
  打印异常信息. (type, value, traceback)为sys.exc_info()返回的元组.和print_tb不同的是:

- 如果traceback不为空, 打印栈头信息(即最近被调用的信息).

- 在栈的信息后打印异常类型和常的参数.

- 如果是语法错误, 会打印对应的代码行数, 用”^”指明语法错误的位置.


    print "*** print_exception:"
traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
  输出:


*** print_exception:
Traceback (most recent call last):
File "t.py", line 13, in <module>
mock()
File "t.py", line 4, in mock
lumberjack()
IndexError: tuple index out of range

traceback.print_exc([limit[, file]])
  print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)的简写.


    print "*** print_exc:"
traceback.print_exc()
  输出:


*** print_exc:
Traceback (most recent call last):
File "t.py", line 13, in <module>
mock()
File "t.py", line 4, in mock
lumberjack()
File "t.py", line 7, in lumberjack
bright_side_of_death()
File "t.py", line 10, in bright_side_of_death
return tuple()[1]
IndexError: tuple index out of range

traceback.format_exc([limit])
  类似于print_exc(limit), 但是返回字符串而不是输出到file.


    print "*** format_exc, first and last line:"
formatted_lines = traceback.format_exc().splitlines()
print formatted_lines[0]
print formatted_lines[-1]
  输出:


*** format_exc, first and last line:
Traceback (most recent call last):
IndexError: tuple index out of range

traceback.format_exception(type, value, tb[, limit])
  格式化栈信息和异常信息. 返回一个列表, 包括代码文件和代码行, 以及异常信息.


    print "*** format_exception:"
print repr(traceback.format_exception(exc_type, exc_value, exc_traceback))
  输出:


['Traceback (most recent call last):\n', '  File "t.py", line 13, in <module>\n    mock()\n', '  File "t.py", line 10, in mock\n    lumberjack()\n', '  File "t.py", line 4, in lumberjack\n    bright_side_of_death()\n', '  File "t.py", line 7, in bright_side_of_death\n    return tuple()[0]\n', 'IndexError: tuple index out of range\n']

traceback.extract_tb(traceback[, limit])
  返回一个跟踪对象(traceback)的元组列表. 元组内容为(filename, line number, function name, text).


    print "*** extract_tb:"
print repr(traceback.extract_tb(exc_traceback))
  输出:


[('t.py', 13, '<module>', 'mock()'), ('t.py', 4, 'mock', 'lumberjack()'), ('t.py', 7, 'lumberjack', 'bright_side_of_death()'), ('t.py', 10, 'bright_side_of_death', 'return tuple()[1]')]

traceback.extract_stack([f[, limit]])
  返回当前栈帧的原始跟踪(traceback)对象的信息, 格式和extract_tb一样, 元组内容为(filename, line number, function name, text).


    print "*** extract_stack:"
print traceback.extract_stack()
  输出:


*** extract_stack:
[('t.py', 47, '<module>', 'print traceback.extract_stack()')]

traceback.format_list(list)
  按照list对应的项, 返回一个元组列表, 形式为同extract_tb()或者extract_stack()返回的一样. 元组内容为(filename, line number, function name, text)

将extract_tb()或者extract_stack()返回的list进行格式化.


print traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'), ('eggs.py', 42, 'eggs', 'return "bacon"')])
  输出:


['  File "spam.py", line 3, in <module>\n    spam.eggs()\n', '  File "eggs.py", line 42, in eggs\n    return "bacon"\n']


traceback.format_tb(tb[, limit])
  format_list(extract_tb(tb, limit))的简写.
traceback.format_stack([f[, limit]])
  format_list(extract_stack(f, limit))的简写
traceback.tb_lineno(tb)
  返回traceback对象设置的行数
实例


import sys, traceback
def mock():
lumberjack()
def lumberjack():
bright_side_of_death()
def bright_side_of_death():
return tuple()[1]
try:
mock()
except IndexError:
exc_type, exc_value, exc_traceback = sys.exc_info()
print "*** print sys.exc_info:"
print 'exc_type is: %s, exc_value is: %s, exc_traceback is: %s' % (exc_type, exc_value, exc_traceback)
print "-" *  100
print "*** print_tb:"
traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
print "-" *  100
print "*** print_exception:"
traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
print "-" *  100
print "*** print_exc:"
traceback.print_exc()
print "-" *  100
print "*** format_exc, first and last line:"
formatted_lines = traceback.format_exc().splitlines()
print formatted_lines[0]
print formatted_lines[-1]
print "-" *  100
print "*** format_exception:"
print repr(traceback.format_exception(exc_type, exc_value, exc_traceback))
print "-" *  100
print "*** extract_tb:"
print repr(traceback.extract_tb(exc_traceback))
print "-" *  100
print "*** extract_stack:"
print traceback.extract_stack()
print "-" *  100
print "*** format_tb:"
print repr(traceback.format_tb(exc_traceback))
print "-" *  100
print "*** tb_lineno:", exc_traceback.tb_lineno
print traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'), ('eggs.py', 42, 'eggs', 'return "bacon"')])
  输出:


*** print sys.exc_info:
exc_type is: <type 'exceptions.IndexError'>, exc_value is: tuple index out of range, exc_traceback is: <traceback object at 0x7f7d659bab48>
----------------------------------------------------------------------------------------------------
*** print_tb:
File "t.py", line 13, in <module>
mock()
----------------------------------------------------------------------------------------------------
*** print_exception:
Traceback (most recent call last):
File "t.py", line 13, in <module>
mock()
File "t.py", line 4, in mock
lumberjack()
IndexError: tuple index out of range
----------------------------------------------------------------------------------------------------
*** print_exc:
Traceback (most recent call last):
File "t.py", line 13, in <module>
mock()
File "t.py", line 4, in mock
lumberjack()
File "t.py", line 7, in lumberjack
bright_side_of_death()
File "t.py", line 10, in bright_side_of_death
return tuple()[1]
IndexError: tuple index out of range
----------------------------------------------------------------------------------------------------
*** format_exc, first and last line:
Traceback (most recent call last):
IndexError: tuple index out of range
----------------------------------------------------------------------------------------------------
*** format_exception:
['Traceback (most recent call last):\n', '  File "t.py", line 13, in <module>\n    mock()\n', '  File "t.py", line 4, in mock\n    lumberjack()\n', '  File "t.py", line 7, in lumberjack\n    bright_side_of_death()\n', '  File "t.py", line 10, in bright_side_of_death\n    return tuple()[1]\n', 'IndexError: tuple index out of range\n']
----------------------------------------------------------------------------------------------------
*** extract_tb:
[('t.py', 13, '<module>', 'mock()'), ('t.py', 4, 'mock', 'lumberjack()'), ('t.py', 7, 'lumberjack', 'bright_side_of_death()'), ('t.py', 10, 'bright_side_of_death', 'return tuple()[1]')]
----------------------------------------------------------------------------------------------------
*** extract_stack:
[('t.py', 47, '<module>', 'print traceback.extract_stack()')]
----------------------------------------------------------------------------------------------------
*** format_tb:
['  File "t.py", line 13, in <module>\n    mock()\n', '  File "t.py", line 4, in mock\n    lumberjack()\n', '  File "t.py", line 7, in lumberjack\n    bright_side_of_death()\n', '  File "t.py", line 10, in bright_side_of_death\n    return tuple()[1]\n']
----------------------------------------------------------------------------------------------------
*** tb_lineno: 13
['  File "spam.py", line 3, in <module>\n    spam.eggs()\n', '  File "eggs.py", line 42, in eggs\n    return "bacon"\n']


<script type="text/javascript">
$(function () {
$('pre.prettyprint code').each(function () {
var lines = $(this).text().split('\n').length;
var $numbering = $('<ul/>').addClass('pre-numbering').hide();
$(this).addClass('has-numbering').parent().append($numbering);
for (i = 1; i <= lines; i++) {
$numbering.append($('<li/>').text(i));
};
$numbering.fadeIn(1700);
});
});
</script>         
版权声明:本文为博主原创文章,未经博主允许不得转载。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-374269-1-1.html 上篇帖子: Python随笔之CSRF问题解决办法 下篇帖子: python 取得当前用户的Home目录
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表