Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a spurious print statement?

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?

like image 598
xorsyst Avatar asked May 25 '17 09:05

xorsyst


1 Answers

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
like image 96
Bartek Jablonski Avatar answered Oct 05 '22 23:10

Bartek Jablonski