问题
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.
回答1:
A SyntaxError in a Python file like the above is raised before your program even begins to run: Python files are compiled just like in any other compiled language - if the parser or compiler can't find sense in your Python file, no executable bytecode is generated, therefore the program does not run.
The correct way to have an exception generated on purpose in your code - from simple test cases like yours, up to implementing complex flow control patterns, is to use the Pyton command raise
.
Just leave your print there, and a line like this at the end:
raise Exception
Then you can see that your trick will work.
Your program could fail in runtime in many other ways without an explict raise, like, if you force a division by 0, or simply try to use an unassigned (and therefore "undeclared") variable - but a deliberate SyntaxError will have the effect that the program never runs to start with - not even the first few lines.
回答2:
This works
sys.stdout = open('out.log', 'w')
sys.stderr = sys.stdout
来源:https://stackoverflow.com/questions/38776104/redirect-stdout-and-stderr-to-same-file-using-python