You can replace one the standard output streams with something that traces invocations of write()
:
import sys
import traceback
class FileTracer(object):
def __init__(self, out):
self.out = out
def write(self, data):
traceback.print_stack(None, None, sys.__stderr__)
self.out.write(data)
def flush(self):
self.out.flush()
def close(self):
self.out.close()
sys.stderr = FileTracer(sys.stderr)
sys.stderr.write("trigger\n")
sys.stderr.flush()
Note that I'm using __stderr__
to avoid loops.