filename and line number of python script

前端 未结 9 1456
醉话见心
醉话见心 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:26

    Better to use sys also-

    print dir(sys._getframe())
    print dir(sys._getframe().f_lineno)
    print sys._getframe().f_lineno
    

    The output is:

    ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'f_back', 'f_builtins', 'f_code', 'f_exc_traceback', 'f_exc_type', 'f_exc_value', 'f_globals', 'f_lasti', 'f_lineno', 'f_locals', 'f_restricted', 'f_trace']
    ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
    14
    
    0 讨论(0)
  • 2020-11-28 02:28

    In Python 3 you can use a variation on:

    def Deb(msg = None):
      print(f"Debug {sys._getframe().f_back.f_lineno}: {msg if msg is not None else ''}")
    

    In code, you can then use:

    Deb("Some useful information")
    Deb()
    

    To produce:

    123: Some useful information
    124:
    

    Where the 123 and 124 are the lines that the calls are made from.

    0 讨论(0)
  • 2020-11-28 02:34

    Filename:

    __file__
    # or
    sys.argv[0]
    

    Line:

    inspect.currentframe().f_lineno
    

    (not inspect.currentframe().f_back.f_lineno as mentioned above)

    0 讨论(0)
  • 2020-11-28 02:37

    Just to contribute,

    there is a linecache module in python, here is two links that can help.

    linecache module documentation
    linecache source code

    In a sense, you can "dump" a whole file into its cache , and read it with linecache.cache data from class.

    import linecache as allLines
    ## have in mind that fileName in linecache behaves as any other open statement, you will need a path to a file if file is not in the same directory as script
    linesList = allLines.updatechache( fileName ,None)
    for i,x in enumerate(lineslist): print(i,x) #prints the line number and content
    #or for more info
    print(line.cache)
    #or you need a specific line
    specLine = allLines.getline(fileName,numbOfLine)
    #returns a textual line from that number of line
    

    For additional info, for error handling, you can simply use

    from sys import exc_info
    try:
         raise YourError # or some other error
    except Exception:
         print(exc_info() )
    
    0 讨论(0)
  • 2020-11-28 02:37

    Here's what works for me to get the line number in Python 3.7.3 in VSCode 1.39.2 (dmsg is my mnemonic for debug message):

    import inspect
    
    def dmsg(text_s):
        print (str(inspect.currentframe().f_back.f_lineno) + '| ' + text_s)
    

    To call showing a variable name_s and its value:

    name_s = put_code_here
    dmsg('name_s: ' + name_s)
    

    Output looks like this:

    37| name_s: value_of_variable_at_line_37
    
    0 讨论(0)
  • 2020-11-28 02:42

    Handy if used in a common file - prints file name, line number and function of the caller:

    import inspect
    def getLineInfo():
        print(inspect.stack()[1][1],":",inspect.stack()[1][2],":",
              inspect.stack()[1][3])
    
    0 讨论(0)
提交回复
热议问题