In C++, I can print debug output like this:
printf( "FILE: %s, FUNC: %s, LINE: %d, LOG: %s\n", __FILE__, __FUNCTION__, __LINE__, logmessage );
How can I do something similar in Python?
Use for loop with enumerate() function to get a line and its number. The enumerate() function adds a counter to an iterable and returns it in enumerate object. Pass the file pointer returned by the open() function to the enumerate() . The enumerate() function adds a counter to each line.
The Python print() function takes in any number of parameters, and prints them out on one line of text. The items are each converted to text form, separated by spaces, and there is a single '\n' at the end (the "newline" char). When called with zero parameters, print() just prints the '\n' and nothing else.
There is a module named inspect
which provides these information.
Example usage:
import inspect def PrintFrame(): callerframerecord = inspect.stack()[1] # 0 represents this line # 1 represents line at caller frame = callerframerecord[0] info = inspect.getframeinfo(frame) print(info.filename) # __FILE__ -> Test.py print(info.function) # __FUNCTION__ -> Main print(info.lineno) # __LINE__ -> 13 def Main(): PrintFrame() # for this line Main()
However, please remember that there is an easier way to obtain the name of the currently executing file:
print(__file__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With