zoukankan      html  css  js  c++  java
  • __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)

  • 相关阅读:
    Mac配置docker阿里云加速器
    Docker初学笔记
    Mac下载安装Tomcat
    MySQL
    monkey
    Git基本使用
    yaml语法
    PAT_B数素数 (20)
    PAT_B1002数字分类
    PAT基础编程练习
  • 原文地址:https://www.cnblogs.com/xuxm2007/p/1858152.html
Copyright © 2011-2022 走看看