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
$ python myfile.py &> out.txt
to do the same task that I want, but I need to do it from the Python script itself.
I looked into the questions Redirect subprocess stderr to stdout, How to redirect stderr in Python?, and Example 10.10 from here, and then I tried the following:
import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock
print "a"
which rightly prints the letter "a" in the file out.txt; however, when I try the following:
import sys
fsock = open('out.txt', 'w')
sys.stdout = sys.stderr = fsock
print "a # missing end quote, will give error
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.
Update: As pointed out in the answers and comments below, that SyntaxError will always output to screen, I replaced the line
print "a # missing end quote, will give error
by
print 1/0 # Zero division error
The ZeroDivisionError is output to file, as I wanted to have it in my question.
This works
sys.stdout = open('out.log', 'w')
sys.stderr = sys.stdout
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With