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
source share