pengdu pengdu - 1 year ago 62
Python Question

How to determine file, function and line number?

In C++, I can print debug output like this:

"FILE: %s, FUNC: %s, LINE: %d, LOG: %s\n",

How can I do something similar in Python?

Answer Source

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__     ->
  print info.function                       # __FUNCTION__ -> Main
  print info.lineno                         # __LINE__     -> 13

def Main():
  PrintFrame()                              # for this line


However, please remember that there is an easier way to obtain the name of the currently executing file:

print __file__
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download