Python stack

本文介绍如何使用Python内置函数sys._getframe()获取当前函数的调用堆栈信息,并展示了具体的实现代码示例。

用 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.youkuaiyun.com/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解密

转载于:https://www.cnblogs.com/moonflow/archive/2012/03/09/2388305.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值