filename and line number of python script

前端 未结 9 1457
醉话见心
醉话见心 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条回答
  • 2020-11-28 02:42
    import inspect    
    
    file_name = __FILE__
    current_line_no = inspect.stack()[0][2]
    current_function_name = inspect.stack()[0][3]
    
    #Try printing inspect.stack() you can see current stack and pick whatever you want 
    
    0 讨论(0)
  • 2020-11-28 02:47

    Thanks to mcandre, the answer is:

    #python3
    from inspect import currentframe, getframeinfo
    
    frameinfo = getframeinfo(currentframe())
    
    print(frameinfo.filename, frameinfo.lineno)
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
提交回复
热议问题