Python debugging: get filename and line number from which a function is called?

前端 未结 4 1901
误落风尘
误落风尘 2020-12-24 01:12

I\'m currently building quite a complex system in Python, and when I\'m debugging I often put simple print statements in several scripts. To keep an overview I often also wa

4条回答
  •  一整个雨季
    2020-12-24 01:27

    Just put the code you posted into a function:

    from inspect import currentframe, getframeinfo
    
    def my_custom_debuginfo(message):
        print getframeinfo(currentframe()).filename + ':' + str(getframeinfo(currentframe()).lineno) + ' - ', message
    

    and then use it as you want:

    # ... some code here ...
    my_custom_debuginfo('what I actually want to print out here')
    # ... more code ...
    

    I recommend you put that function in a separate module, that way you can reuse it every time you need it.

提交回复
热议问题