Posted By: user234932
How do I redirect stdout to an arbitrary file in Python?
When a long-running Python script (e.g, web application) is started from within the ssh session and backgounded, and the ssh session is closed, the application will raise IOError and fail the moment it tries to write to stdout. I needed to find a way to make the application and modules output to a file rather than stdout to prevent failure due to IOError. Currently, I employ nohup to redirect output to a file, and that gets the job done, but I was wondering if there was a way to do it without using nohup, out of curiosity.
I have already tried
sys.stdout = open('somefile', 'w'), but this does not seem to prevent some external modules from still outputting to terminal (or maybe the
sys.stdout = ... line did not fire at all). I know it should work from simpler scripts I’ve tested on, but I also didn’t have time yet to test on a web application yet.
If you want to do the redirection within the Python script, setting
sys.stdout to a file object does the trick:
import sys sys.stdout = open('file', 'w') print('test') sys.stdout.close()
A far more common method is to use shell redirection when executing (same on Windows and Linux):
$ python foo.py > file