In Python 2.x, you can kind of intercept a print statement by replacing sys.stdout
with an object that satisfies the interface of a file (think duck typing). A simple start:
import inspect
import sys
class OutputHook(object):
def __init__(self, stdout):
self._stdout = stdout
def write(self, text):
frame = inspect.currentframe(1)
try:
class_name = frame.f_locals['self'].__class__.__name__ + "."
except KeyError:
class_name = ""
self._stdout.write("writing to sys.stdout at "
"{}{}() in line {}:\n{}\n".format(
class_name,
frame.f_code.co_name,
frame.f_lineno,
repr(text)))
def test():
print "BBB"
class Test:
def bla(self):
print "Hello"
sys.stdout = OutputHook(sys.stdout)
print "aaa"
test()
Test().bla()
You will get as output:
writing to sys.stdout at <module>() in line 33:
'aaa'
writing to sys.stdout at <module>() in line 33:
'\n'
writing to sys.stdout at test() in line 25:
'BBB'
writing to sys.stdout at test() in line 25:
'\n'
writing to sys.stdout at Test.bla() in line 29:
'Hello'
writing to sys.stdout at Test.bla() in line 29:
'\n'
You could add a check if the written text is your pattern and start the debugger, or just break, for example:
if text.startwith("funny"):
pdb.set_trace()