__FUNCTION__ and __LINE__ in Python

本文介绍如何在Python中模拟C预处理器宏__FUNCTION__和__LINE__的功能,利用inspect模块获取当前函数名和行号,便于进行日志记录和调试。

When you want to log something, C pre-processor macros __FUNCTION__ and __LINE__ are quite helpful (althogh the first is a GNU extension for GCC, AFAIK). Python have the __name__ pseudo-variable with the current namespace, but isn’t quite helpful when you want to find where things are going. Fortunately, you can “emulate” __FUNCTION__ and __LINE__ in Python, using the inspect module.

def __line__ ():
    caller = inspect.stack()[1]
    return int (caller[2])

def __function__ ():
    caller = inspect.stack()[1]
    return caller[3]

我的测试代码
import inspect

def all():
	caller = inspect.stack()
	print len(caller)
	print caller[0]
	print caller[1]
	print caller[2]

def main():
	all()

if __name__=='__main__':
	main()

输出
> "D:\Python25\python.exe"  "C:\Documents and Settings\xingming.xuxm\My Documents\Untitled 2.py" 
3
(<frame object at 0x00CBA368>, 'C:\\Documents and Settings\\xingming.xuxm\\My Documents\\Untitled 2.py', 6, 'all', ['\tcaller = inspect.stack()\n'], 0)
(<frame object at 0x00CBBA38>, 'C:\\Documents and Settings\\xingming.xuxm\\My Documents\\Untitled 2.py', 13, 'main', ['\tall()\n'], 0)
(<frame object at 0x00CAD8B0>, 'C:\\Documents and Settings\\xingming.xuxm\\My Documents\\Untitled 2.py', 16, '<module>', ['\tmain()'], 0)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值