您始终可以使用 traceback.format_exc().splitlines() 创建一个列表:
#!/usr/bin/env python3
import traceback
def thing_that_will_blowup():
assert False is True
def catch_it_blowup():
try:
thing_that_will_blowup()
except AssertionError:
exception_data = traceback.format_exc().splitlines()
for index, line in enumerate(exception_data):
if 'File' in line and os.path.basename(__file__) in line:
print("{} - {}".format(index, line))
print("{} - {}".format(index + 1, exception_data[index + 1]))
if __name__ == "__main__":
catch_it_blowup()
返回:
1 - File "split_stacktrace.py", line 11, in check_it_blowup
2 - thing_that_will_blowup()
3 - File "split_stacktrace.py", line 6, in thing_that_will_blowup
4 - assert False is True
您仍然需要从那里识别和切片。