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
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.
This works
sys.stdout = open('out.log', 'w')
sys.stderr = sys.stdout