Finding a print statement in Python

This article can prove very valuable in doing that. Look for the line events and extract the method name from the frame ( if I remember correctly ). More information can be found here


You asked about static solutions. Here's a dynamic one. Suppose you run the code and see an errant print or write to sys.stdout, and want to know where it comes from. You can replace sys.stdout and let the exception traceback help you:

>>> import sys
>>> def go():
...   sys.stdout = None
...   print "Hello!"
... 
>>> go()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in go
AttributeError: 'NoneType' object has no attribute 'write'
>>> print "Here"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'write'
>>> 

For something a bit more sophisticated, replace 'sys.stdout' with something which reports where the print statement is located. I'll use traceback.print_stack() to show the full stack, but you can do other things like using sys._getframe() to look up one stack level in order to get the line number and filename.

import sys
import traceback

class TracePrints(object):
  def __init__(self):    
    self.stdout = sys.stdout
  def write(self, s):
    self.stdout.write("Writing %r\n" % s)
    traceback.print_stack(file=self.stdout)

sys.stdout = TracePrints()

def a():
  print "I am here"

def b():
  a()

b()

Here's the output

Writing 'I am here'
  File "stdout.py", line 19, in <module>
    b()
  File "stdout.py", line 17, in b
    a()
  File "stdout.py", line 14, in a
    print "I am here"
  File "stdout.py", line 9, in write
    traceback.print_stack(file=self.stdout)
Writing '\n'
  File "stdout.py", line 19, in <module>
    b()
  File "stdout.py", line 17, in b
    a()
  File "stdout.py", line 14, in a
    print "I am here"
  File "stdout.py", line 9, in write
    traceback.print_stack(file=self.stdout)

If you go this route, see also the 'linecache' module, which you can use to print the contents of the line. Take a look at the implementation of traceback.print_stack for details of how to do that.

Tags:

Python