Is there a trick to printing on inline printing using pdb?

In principle, the title.

I am trying to trace where false printing occurs in a large code base, and I would like to break or somehow get a stack trace whenever printing "occurs". Any ideas?

+3
source share
2 answers

In this particular case, you can redirect stdoutto a helper class that prints the output and its caller. You can also break up one of your methods.

Full example:

import sys
import inspect

class PrintSnooper:
    def __init__(self, stdout):
        self.stdout = stdout
    def caller(self):
        return inspect.stack()[2][3]
    def write(self, s):
        self.stdout.write("printed by %s: " % self.caller())
        self.stdout.write(s)
        self.stdout.write("\n")

def test():
    print 'hello from test'

def main():
    # redirect stdout to a helper class.
    sys.stdout = PrintSnooper(sys.stdout)
    print 'hello from main'
    test()

if __name__ == '__main__':
    main()

Conclusion:

printed by main: hello from main
printed by main: 

printed by test: hello from test
printed by test: 

You can also simply print inspect.stack()it if you need more detailed information.

+3
source

, , sys.stdout, , streamwriter, codecs.getwriter('utf8'). write pdb. write .

import codecs
import sys

writer = codecs.getwriter('utf-8')(sys.stdout) # sys.stdout.detach() in python3
old_write = writer.write

def write(data):
    print >>sys.stderr, 'debug:', repr(data)
    # or check data + pdb.set_trace()
    old_write(data)

writer.write = write
sys.stdout = writer

print 'spam', 'eggs'
+1

All Articles