Python stack

用 sys._getframe() 函数获取调用堆栈帧信息

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

def test(depth = 0):
frame = sys._getframe(depth)
code = frame.f_code

print "frame depth = ", depth
print "func name = ", code.co_name
print "func filename = ", code.co_filename
print "func lineno = ", code.co_firstlineno
print "func locals = ", frame.f_locals

def main():
test(0)
print "--------"
test(1)

if __name__ == "__main__":
main()

输出:
frame depth = 0
func name = test
func filename = D:\...\main.py
func lineno = 6
func locals = {'frame': <frame object at 0x01209880>, 'code': <code object test at 011EBF98, file "D:\...\main.py", line 6>, 'depth': 0}
--------
frame depth = 1
func name = main
func filename = D:\...\main.py
func lineno = 16
func locals = {}

重点链接

http://docs.python.org/library/inspect.html#inspect-stack
http://hg.python.org/cpython/file/2.7/Lib/inspect.py
http://blog.csdn.net/program_think/article/details/7240881
http://www.okpython.com/thread-2429-1-1.html
http://code.activestate.com/lists/python-list/361744/
http://hi.baidu.com/limodou/blog/item/83f4b21937ed174043a9adb5.html Python的动态性
http://autumn-sea.appspot.com/page/agphdXR1bW4tc2Vhcg0LEgRCbG9nGNGcgQEM
http://nedbatchelder.com/blog/200804/the_structure_of_pyc_files.html Pyc解密

posted @ 2012-03-09 21:13  yarpee  阅读(478)  评论(0编辑  收藏  举报