How to capture Python interpreter's and/or CMD.EXE's output from a Python script?

后端 未结 5 1666
感动是毒
感动是毒 2020-12-06 12:52
  1. Is it possible to capture Python interpreter\'s output from a Python script?
  2. Is it possible to capture Windows CMD\'s output from a Python script?
5条回答
  •  甜味超标
    2020-12-06 13:22

    I think I can point you to a good answer for the first part of your question.

    1.  Is it possible to capture Python interpreter's output from a Python script?

    The answer is "yes", and personally I like the following lifted from the examples in the PEP 343 -- The "with" Statement document.

    from contextlib import contextmanager
    import sys
    
    @contextmanager
    def stdout_redirected(new_stdout):
        saved_stdout = sys.stdout
        sys.stdout = new_stdout
        try:
            yield None
        finally:
            sys.stdout.close()
            sys.stdout = saved_stdout
    

    And used like this:

    with stdout_redirected(open("filename.txt", "w")):
        print "Hello world"
    

    A nice aspect of it is that it can be applied selectively around just a portion of a script's execution, rather than its entire extent, and stays in effect even when unhandled exceptions are raised within its context. If you re-open the file in append-mode after its first use, you can accumulate the results into a single file:

    with stdout_redirected(open("filename.txt", "w")):
        print "Hello world"
    
    print "screen only output again"
    
    with stdout_redirected(open("filename.txt", "a")):
        print "Hello world2"
    

    Of course, the above could also be extended to also redirect sys.stderr to the same or another file. Also see this answer to a related question.

提交回复
热议问题