gpt4 book ai didi

python - 如何在Python中缩进堆栈跟踪?

转载 作者:行者123 更新时间:2023-11-30 23:46:06 25 4
gpt4 key购买 nike

环境 - win7 机器上的 Python 2.7.2。我的技能水平 - 菜鸟

我正在使用以下内容来捕获并打印异常堆栈跟踪 -

def logerr(stmt, e):
try:
##do something

except:
print '##EXCEPTION in logging: '
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stdout)

输出是-

##EXCEPTION in logging: 
Traceback (most recent call last):
File "C:\Users\amurty\Desktop\dev\eclipse\workspace\hhs\FeedSearch\src\main\main.py", line 18, in main
log()
TypeError: log() takes exactly 1 argument (0 given)

我想缩进堆栈跟踪。所以输出应该是这样的 -

##EXCEPTION in logging: 
Traceback (most recent call last):
File "C:\Users\amurty\Desktop\dev\eclipse\workspace\hhs\FeedSearch\src\main\main.py", line 18, in main
log()
TypeError: log() takes exactly 1 argument (0 given)

我怎样才能实现这个目标。pprint 或 textwrap 模块在这里有帮助吗?

最佳答案

试试这个:

import traceback

def logerr(stmt, e):
try:
##do something

except:
print '##EXCEPTION in logging: '
for line in traceback.format_exception().splitlines():
print ' ' + line

关于python - 如何在Python中缩进堆栈跟踪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9204044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com