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():
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.
source
share