Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a trick to break on the print builtin with pdb?

Basically, the title.

I am trying to trace down where a spurious print happens in a large codebase, and I would like to break, or somehow get a stack trace whenever a print "happens." Any ideas?

like image 487
user961826 Avatar asked May 24 '12 17:05

user961826


People also ask

How do I set break point in pdb?

Optionally, you can also tell pdb to break only when a certain condition is true. Use the command b (break) to set a breakpoint. You can specify a line number or a function name where execution is stopped. If filename: is not specified before the line number lineno , then the current source file is used.

How do you get out of a loop in pdb?

Once you get you pdb prompt . Just hit n (next) 10 times to exit the loop.

How do you add a break point in Python?

It's easy to set a breakpoint in Python code to i.e. inspect the contents of variables at a given line. Add import pdb; pdb. set_trace() at the corresponding line in the Python code and execute it. The execution will stop at the breakpoint.

What is breakpoint () Python?

Python breakpoint() - Stop Debugging Python sys. breakpointhook() function uses environment variable PYTHONBREAKPOINT to configure the debugger. If unset, the default PDB debugger is used. If it's set to “0” then the function returns immediately and no code debugging is performed.


1 Answers

For this particular case you can redirect stdout to a helper class that prints the output and its caller. You can also break on one of its 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()

Output:

printed by main: hello from main
printed by main: 

printed by test: hello from test
printed by test: 

You can also just print inspect.stack() if you need more thorough information.

like image 174
Eduardo Ivanec Avatar answered Sep 24 '22 06:09

Eduardo Ivanec