pythondebuggingstdout

Find source code line which prints some debugging stuff on stdout


I have a huge code base before me, and can't find the place where this strings gets printed to stdout:

[{}]

I can reproduce it, but searching the relevant code line was not successful up to now.

I guess this was added accidentally by a developer to aid debugging.

Any clue how to find the matching code line which emits this string to stdout?


Solution

  • You can find the relevant source code line be raising an exception, if this line gets emitted like this:

    class WrapperOfStdout():
        def __init__(self, old_stdout):
            self.old_stdout=old_stdout
    
        def write(self, data):
            assert not '{}' in data, data
            return self.old_stdout.write(data)
    
        def __getattr__(self, name):
            return getattr(self.old_stdout, name)
    

    Add this wrapper into your script, and wrap stdout as early as possible (soon after main):

    sys.stdout=WrapperOfStdout(sys.stdout)
    

    You will get an Exception like this:

    Traceback (most recent call last):
      File "/home/u/src/foo-bar/foo_bar/utils/common.py", line 94, in issue_to_tar
        meta = issuemeta(request, issue).encode('utf8')
      File "/home/u/src/foo/foo/views/issue/view.py", line 198, in issue_meta
        div = index_model.view(issue, request)
      File "/home/u/src/foo/foo/utils/indexutils.py", line 96, in view
        form = form_cls(request, issue, None, prefix=prefix)
      File "/home/u/src/foo-x/foo_x/logic/forms.py", line 115, in __init__
        print(fake_initial)
      File "/home/u/tmp/issue_to_tar.py", line 13, in write
        assert not '{}' in data, data
    AssertionError: [{}]
    

    Now you see where the unwanted output happens. In this case it is logic/forms.py line 115.