How to find a false print instruction?

I am debugging a large Python codebase. Somewhere a piece of code prints {} for the console, this is probably the old debugging code that was left by accident.

Since this is the only console output that does not go through the registrar, is there any way to find the culprit? Perhaps overriding what the print statement does, so can I throw an exception?

+5
source share
1 answer

Try redirecting sys.stdout to a custom stream handler (see Redirect stdout to a file in Python? ), Where you can override the 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 a good trace:

 λ 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 
+5
source

Source: https://habr.com/ru/post/1268219/


All Articles