Python debugging, stop at particular output
Question: I have complex python project with lots of modules, loggers, twisted defereds
and other stuff.

And somewhere in the code some line is printed to logs, and I want to find out
where. Usually I just search the codebase for that string, but now that string
is generated dynamically, so is not searchable.

And I wander if there is any way to run python in some debug mode, and tell it
to stop when some pattern will appear in sdout, and then print location in
code where it stopped?


Answer: How about replacing `sys.stdout`?

For example:

    
    
    import sys
    import traceback
    
    
    class StacktraceOnPrint:
    
        def __init__(self, orig_stdout, substring):
            self.orig_stdout = orig_stdout
            self.substring = substring
    
        def write(self, txt):
            if self.substring in txt:
                traceback.print_stack() # OR  import pdb; pdb.set_trace()
            self.orig_stdout.write(txt)
    
    
    sys.stdout = StacktraceOnPrint(sys.stdout, 'blah')
    print 'test ...'
    print 'Hello blah.'
    print 'test ...'
    

**NOTE**
[`traceback.print_stack`](http://docs.python.org/2/library/traceback.html#traceback.print_stack)
uses `sys.stderr`. If you want to catch `sys.stderr`, use different function
(like
[`traceback.format_stack`](http://docs.python.org/2/library/traceback.html#traceback.format_stack)).
Otherwise it recurses forever; causes `RuntimeError: maximum recursion depth
exceeded` ..

