filename and line number of python script

前端 未结 9 1488
醉话见心
醉话见心 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: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() )
    

提交回复
热议问题