filename and line number of python script

前端 未结 9 1495
醉话见心
醉话见心 2020-11-28 01:50

How can I get the file name and line number in python script.

Exactly the file information we get from an exception traceback. In this case without raising an excep

9条回答
  •  旧时难觅i
    2020-11-28 02:48

    Whether you use currentframe().f_back depends on whether you are using a function or not.

    Calling inspect directly:

    from inspect import currentframe, getframeinfo
    
    cf = currentframe()
    filename = getframeinfo(cf).filename
    
    print "This is line 5, python says line ", cf.f_lineno 
    print "The filename is ", filename
    

    Calling a function that does it for you:

    from inspect import currentframe
    
    def get_linenumber():
        cf = currentframe()
        return cf.f_back.f_lineno
    
    print "This is line 7, python says line ", get_linenumber()
    

提交回复
热议问题