Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine file, function and line number?

Tags:

python

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?

like image 303
pengdu Avatar asked Jul 25 '11 01:07

pengdu


People also ask

How do I get the code of a line number 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.

How do you print a line function in Python?

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.


1 Answers

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__) 
like image 102
Tugrul Ates Avatar answered Sep 24 '22 00:09

Tugrul Ates