[python] traceback 으로 이상 스 택 을 가 져 오고 출력 이상 을 포맷 합 니 다.

8788 단어 python 지식python
실현 방식
test.py
#encoding:utf-8

import sys
import traceback

def testerr():
	testerr2()

def testerr2():
	a = "test"
	b = 123
	print(c)	#      ,     
	
try:
	testerr()
except Exception as e:
	exc_type, exc_value, exc_traceback = sys.exc_info()
	frame = traceback.extract_tb(exc_traceback) #        FrameSummary  
	#         
	mapStack = map(str, frame)
	sErrorStack = "
"
.join(mapStack) # traceback.format_exc() print(" :") print(sErrorStack) # print(repr(e)) # lasttb = None while exc_traceback: lasttb = exc_traceback exc_traceback = exc_traceback.tb_next print(" :") print(lasttb.tb_frame.f_locals)

출력 결과:
이상 스 택: NameError ("name" c "is not defined") 부분 변수: {"a": "test", "b": 123}
장식 기 버 전
from functools import wraps

import sys
import traceback

def FormatError(func):
	@wraps(func)
	def Format(*args, **kwargs):
		try:
			func(*args, **kwargs)
		except Exception as e:
			exc_type, exc_value, exc_traceback = sys.exc_info()
			frame = traceback.extract_tb(exc_traceback) #        FrameSummary  
			#         
			mapStack = map(str, frame)
			sErrorStack = "
"
.join(mapStack) print(" :") print(sErrorStack) # print(repr(e)) # lasttb = None while exc_traceback: lasttb = exc_traceback exc_traceback = exc_traceback.tb_next print(" :") print(lasttb.tb_frame.f_locals) return Format @FormatError def testerr(): testerr2() def testerr2(): a = "test" b = 123 print(c) # , testerr()

좋은 웹페이지 즐겨찾기