title: Redirect stdout and stderr to same file using Python
body: <p>I would like to redirect the standard error and standard output of a Python script to the same output file. From the terminal I could use </p>
  
  <pre><code>$ python myfile.py &amp;&gt; out.txt
  </code></pre>
  
  <p>to do the same task that I want, but I need to do it from the Python script itself. </p>
  
  <p>I looked into the questions <a href="https://stackoverflow.com/questions/11495783/redirect-subprocess-stderr-to-stdout">Redirect subprocess stderr to stdout</a>, <a href="https://stackoverflow.com/questions/1956142/how-to-redirect-stderr-in-python">How to redirect stderr in Python?</a>, and Example 10.10 from <a href="http://www.diveintopython.net/scripts_and_streams/stdin_stdout_stderr.html" rel="noreferrer">here</a>, and then I tried the following:</p>
  
  <pre><code>import sys
  fsock = open('out.txt', 'w')
  sys.stdout = sys.stderr = fsock
  
  print "a"
  </code></pre>
  
  <p>which rightly prints the letter "a" in the file out.txt; however, when I try the following:</p>
  
  <pre><code>import sys
  fsock = open('out.txt', 'w')
  sys.stdout = sys.stderr = fsock
  
  print "a   # missing end quote, will give error
  </code></pre>
  
  <p>I get the error message "SyntaxError ..." on the terminal, but not in the file out.txt. What do I need to do to send the SyntaxError to the file out.txt? I do not want to write an Exception, because in that case I have to write too many Exceptions in the script. I am using Python 2.7.</p>
  
  <p>Update: As pointed out in the answers and comments below, that SyntaxError will always output to screen, I replaced the line</p>
  
  <pre><code>print "a   # missing end quote, will give error
  </code></pre>
  
  <p>by</p>
  
  <pre><code>print 1/0  # Zero division error
  </code></pre>
  
  <p>The ZeroDivisionError is output to file, as I wanted to have it in my question.</p>