When working on real-world applications or side projects, we often have to retrieve line numbers and filenames for debugging purposes. Generally, this is done to understand what code is getting executed when or to analyse the flow of control of any application. In this article, we will learn how to get a line number and the filename of the Python script using Python.
Get the Filename and a Line Number in Python
To get the filename and a line number from the executing Python script, we can use the
inspect module Python. The
inspect module contains several utilities to fetch information about objects, classes, methods, functions, frame objects, and code objects. This library has a
getframeinfo() method that retrieves information about a frame or a traceback object. This method accepts a
frame argument about which it retrieves details. The
currentFrame() method returns the frame object for the caller’s stack frame. We can use these utilities for our use case. Refer to the following Python code to understand the usage.
from inspect import currentframe, getframeinfo frame = getframeinfo(currentframe()) filename = frame.filename line = frame.lineno print("Filename:", filename) print("Line Number:", line)
Filename: full/path/to/file/main.py Line Number: 3
As we can see, the
filename attribute will return the full path to the Python file. In my case, the Python file’s name was
main.py; hence, it shows
main.py in the output. And, the
lineno attribute return the line number at which this
frame = getframeinfo(currentframe()) statement was executed. The mentioned statement was execute at line
3; hence the output has a
3 after the
Line Number label.