__FUNCTION__ and __LINE__ in Python

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)

posted on 2010-10-22 11:45  阿笨猫  阅读(2373)  评论(0编辑  收藏  举报