Created
April 19, 2016 16:46
-
-
Save MOOOWOOO/e6146c4adf871593af9f8ac0ae19be0f to your computer and use it in GitHub Desktop.
程序跟踪装饰器,用于程序运行的时候打印出每一步的运行顺序和调用逻辑
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys,os,linecache | |
| def trace(f): | |
| def globaltrace(frame, why, arg): | |
| if why == "call": | |
| return localtrace | |
| return None | |
| def localtrace(frame, why, arg): | |
| if why == "line": | |
| # record the file name and line number of every trace | |
| filename = frame.f_code.co_filename | |
| lineno = frame.f_lineno | |
| bname = os.path.basename(filename) | |
| print "{}({}): {}".format( bname, lineno, linecache.getline(filename, lineno).strip('\r\n')), | |
| return localtrace | |
| def _f(*args, **kwds): | |
| sys.settrace(globaltrace) | |
| result = f(*args, **kwds) sys.settrace(None) | |
| return result | |
| return _f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment