title: Redirect stdout to a file in Python?
body: <p>How do I redirect stdout to an arbitrary file in Python?</p>
  
  <p>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.</p>
  
  <p>I have already tried <code>sys.stdout = open('somefile', 'w')</code>, but this does not seem to prevent some external modules from still outputting to terminal (or maybe the <code>sys.stdout = ...</code> 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.</p>