5

I'm debugging a large Python codebase. Somewhere, a piece of code is printing {} to console, presumably this is some old debugging code that's been left in by accident.

As this is the only console output that doesn't go through logger, is there any way I can find the culprit? Perhaps by redefining what the print statement does, so I can cause an exception?

xorsyst
  • 7,897
  • 5
  • 39
  • 58
  • 1
    Use grep. Example : `grep -rnw '/path/to/somewhere/' -e 'pattern'`. Ref : https://stackoverflow.com/questions/16956810/how-do-i-find-all-files-containing-specific-text-on-linux – Kajal May 25 '17 at 09:17
  • 1
    If everything else goes through a logger function, can't you just search for `print`? if you're using a decent IDE, it should have a way to search the entire codebase. – Barmar May 25 '17 at 09:18
  • 2
    Search for all `print` statements, disable half of them, re-run. Still there? Disable the other half, etc. – Martijn Pieters May 25 '17 at 09:18
  • I have a *lot* of print statements in the codebase, that are all printing to output files, so it's not quite that simple :( – xorsyst May 25 '17 at 09:19

1 Answers1

5

Try to redirect sys.stdout to custom stream handler (see Redirect stdout to a file in Python?), where you can override write() method.

Try something like this:

import io
import sys
import traceback


class TestableIO(io.BytesIO):

    def __init__(self, old_stream, initial_bytes=None):
        super(TestableIO, self).__init__(initial_bytes)
        self.old_stream = old_stream

    def write(self, bytes):
        if 'bb' in bytes:
            traceback.print_stack(file=self.old_stream)
        self.old_stream.write(bytes)


sys.stdout = TestableIO(sys.stdout)
sys.stderr = TestableIO(sys.stderr)

print('aa')
print('bb')
print('cc')

Then you will get nice traceback:

λ python test.py
aa
  File "test.py", line 22, in <module>
    print('bb')
  File "test.py", line 14, in write
    traceback.print_stack(file=self.old_stream)
bb
cc
Bartek Jablonski
  • 2,649
  • 24
  • 32