I have 3 scripts. one is starttest.py which kicks the execution of methods called in test.py. Methods are defined in module.py.
There are many print statements in each of file and I want to capture each print statement in my log file from Starttest.py file itself. I tried using sys.stdout in starttest.py file but this function only takes print statements from starttest.py file. It does not have any control on test.py and module.py file print statements.
Any suggestions to capture the print statements from all of the files in a single place only?
Before importing anything from
test.pyormodule.py, replace tyesys.stdoutfile object with one of your liking:If you’re running on a Unix-like operating system, there is a safer method that does not need to replace the file object reference. Specially since overwriting
sys.stdoutdoes not guarantee that previous object is destroyed:Note that the above trick is used by almost all daemonization implementations for Python.
Even though not directly related, remember also that you can use your shell to redirect command output to a file (works on Windows too):