This is possible with a decorator such as:
import sys def redirect_stderr_stdout(stderr=sys.stderr, stdout=sys.stdout): def wrap(f): def newf(*args, **kwargs): old_stderr, old_stdout = sys.stderr, sys.stdout sys.stderr = stderr sys.stdout = stdout try: return f(*args, **kwargs) finally: sys.stderr, sys.stdout = old_stderr, old_stdout return newf return wrap
Use as:
@redirect_stderr_stdout(some_logging_stream, the_console): def fun(...):
or, if you do not want to change the source for fun , call it directly as
redirect_stderr_stdout(some_logging_stream, the_console)(fun)
But note that this is not thread safe.
Fred Foo Jul 22 2018-11-21T00: 00Z
source share