Nov-30-2020, 03:54 AM
Which stdout/stderr? Changing them by assigning to sys.stdout/sys.stderr should work the same in a module as it does in the main program.
redirect.py
redirect.py
import sys def redirect(outname, errname): sys.stdout = open(outname, "w") sys.stderr = open(errname, "w") returnMain program that calls the module:
import redirect print("hello") # goes to stdout redirect.redirect("/tmp/redirected.out", "/tmp/redirected.err") print("hello, there") # should go to redirected stdout 5/0 # error should go to redirected stderr
Output:$ python3 test.py
hello
$ cat /tmp/redirected.out
hello, there
$ cat /tmp/redirected.err
Traceback (most recent call last):
File "test.py", line 6, in <module>
5/0 # error should go to redirected stderr
ZeroDivisionError: division by zero