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

后端 未结 5 1654
感动是毒
感动是毒 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:19

    Actually, you definitely can, and it's beautiful, ugly, and crazy at the same time!

    You can replace sys.stdout and sys.stderr with StringIO objects that collect the output.

    Here's an example, save it as evil.py:

    import sys
    import StringIO
    
    s = StringIO.StringIO()
    
    sys.stdout = s
    
    print "hey, this isn't going to stdout at all!"
    print "where is it ?"
    
    sys.stderr.write('It actually went to a StringIO object, I will show you now:\n')
    sys.stderr.write(s.getvalue())
    

    When you run this program, you will see that:

    • nothing went to stdout (where print usually prints to)
    • the first string that gets written to stderr is the one starting with 'It'
    • the next two lines are the ones that were collected in the StringIO object

    Replacing sys.stdout/err like this is an application of what's called monkeypatching. Opinions may vary whether or not this is 'supported', and it is definitely an ugly hack, but it has saved my bacon when trying to wrap around external stuff once or twice.

    Tested on Linux, not on Windows, but it should work just as well. Let me know if it works on Windows!

提交回复
热议问题