Redirect stdout and stderr to same file using Python

后端 未结 2 1475
梦谈多话
梦谈多话 2021-01-20 15:45

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         


        
相关标签:
2条回答
  • 2021-01-20 16:08

    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.

    0 讨论(0)
  • 2021-01-20 16:16

    This works

    sys.stdout = open('out.log', 'w')
    sys.stderr = sys.stdout
    
    0 讨论(0)
提交回复
热议问题