forked from Jueee/PythonStandardLibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib02.11-traceback.py
54 lines (39 loc) · 1.14 KB
/
lib02.11-traceback.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
'''
traceback 模块
traceback 模块允许你在程序里打印异常的跟踪返回(Traceback)信息, 类似未捕获异常时解释器所做的.
[注]
导入 traceback 会清理掉异常状态, 所以最好别在异常处理代码中导入该模块
'''
'''
import traceback
try:
raise(SyntaxError,'example')
except :
traceback.print_exc()
'''
# 使用 traceback 模块将跟踪返回信息复制到字符串
# 使用 StringIO 模块将跟踪返回信息放在字符串中.
import traceback
import io
try:
raise(IOError,'an i/o error occurred')
except:
fp = io.StringIO()
traceback.print_exc(file = fp)
message = fp.getvalue()
print('failure! the error was:', repr(message))
print('---------')
# 使用 traceback Module 模块编码 Traceback 对象
# 可以使用 extract_tb 函数格式化跟踪返回信息, 得到包含错误信息的列表
import traceback
import sys
def function():
raise(IOError,'an i/o error occurred')
try:
function()
except:
info = sys.exc_info()
for file, lineno, function, text in traceback.extract_tb(info[2]):
print(file, 'line', lineno, 'in', function)
print('=>', repr(text))
print('** %s:%s' % info[:2])