Redirect stdout and stderr to same file using Python

喜欢而已 提交于 2019-12-02 02:56:31

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!