<ol>
<li>Is it possible to capture Python interpreter's output from a Python script?</li>
<li>Is it possible to capture Windows CMD's output from a Python script?</li>
</ol>

<p>If so, which librar(y|ies) should I look into?</p>

[{'answer_id': 24939, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 0, 'selected': False, 'text': "<p>In which context are you asking?</p>\n\n<p>Are you trying to capture the output from a program you start on the command line?</p>\n\n<p>if so, then this is how to execute it:</p>\n\n<pre><code>somescript.py | your-capture-program-here\n</code></pre>\n\n<p>and to read the output, just read from standard input.</p>\n\n<p>If, on the other hand, you're executing that script or cmd.exe or similar from within your program, and want to wait until the script/program has finished, and capture all its output, then you need to look at the library calls you use to start that external program, most likely there is a way to ask it to give you some way to read the output and wait for completion.</p>\n"}, {'answer_id': 24942, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 1, 'selected': False, 'text': '<p>You want <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow noreferrer">subprocess</a>. Look specifically at Popen in 17.1.1 and communicate in 17.1.2.</p>\n'}, {'answer_id': 24949, 'author': 'Henrik Gustafsson', 'author_id': 2010, 'author_profile': 'https://Stackoverflow.com/users/2010', 'pm_score': 4, 'selected': True, 'text': '<p>If you are talking about the python interpreter or CMD.exe that is the \'parent\' of your script then no, it isn\'t possible. In every POSIX-like system (now you\'re running Windows, it seems, and that might have some quirk I don\'t know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:</p>\n\n<pre><code>python script_a.py | python script_b.py\n</code></pre>\n\n<p>This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on <a href="http://en.wikipedia.org/wiki/Standard_streams" rel="nofollow noreferrer">standard streams</a> on Wikipedia.</p>\n\n<p>If you\'re talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):</p>\n\n<pre><code>import subprocess\n# Of course you can open things other than python here :)\nprocess = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nx = process.stderr.readline()\ny = process.stdout.readline()\nprocess.wait()\n</code></pre>\n\n<p>See the Python <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow noreferrer">subprocess</a> module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard <a href="http://docs.python.org/lib/bltin-file-objects.html" rel="nofollow noreferrer">file objects</a>.</p>\n\n<p>For use with pipes, reading from standard input as <a href="https://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939">lassevk</a> suggested you\'d do something like this:</p>\n\n<pre><code>import sys\nx = sys.stderr.readline()\ny = sys.stdin.readline()\n</code></pre>\n\n<p>sys.stdin and sys.stdout are standard file objects as noted above, defined in the <a href="http://docs.python.org/lib/module-sys.html" rel="nofollow noreferrer">sys</a> module. You might also want to take a look at the <a href="http://docs.python.org/lib/module-pipes.html" rel="nofollow noreferrer">pipes</a> module.</p>\n\n<p>Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into <a href="http://docs.python.org/lib/poll-objects.html" rel="nofollow noreferrer">polling</a> which unfortunately does not work in windows, but I\'m sure there\'s some alternative out there.</p>\n'}, {'answer_id': 29169, 'author': 'Thomas Vander Stichele', 'author_id': 2900, 'author_profile': 'https://Stackoverflow.com/users/2900', 'pm_score': 2, 'selected': False, 'text': '<p>Actually, you definitely can, and it\'s beautiful, ugly, and crazy at the same time!</p>\n\n<p>You can replace sys.stdout and sys.stderr with StringIO objects that collect the output.</p>\n\n<p>Here\'s an example, save it as evil.py:</p>\n\n<pre><code>import sys\nimport StringIO\n\ns = StringIO.StringIO()\n\nsys.stdout = s\n\nprint "hey, this isn\'t going to stdout at all!"\nprint "where is it ?"\n\nsys.stderr.write(\'It actually went to a StringIO object, I will show you now:\\n\')\nsys.stderr.write(s.getvalue())\n</code></pre>\n\n<p>When you run this program, you will see that:</p>\n\n<ul>\n<li>nothing went to stdout (where print usually prints to)</li>\n<li>the first string that gets written to stderr is the one starting with \'It\'</li>\n<li>the next two lines are the ones that were collected in the StringIO object</li>\n</ul>\n\n<p>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.</p>\n\n<p>Tested on Linux, not on Windows, but it should work just as well.  Let me know if it works on Windows!</p>\n'}, {'answer_id': 3378965, 'author': 'martineau', 'author_id': 355230, 'author_profile': 'https://Stackoverflow.com/users/355230', 'pm_score': 3, 'selected': False, 'text': '<p>I think I can point you to a good answer for the first part of your question. </p>\n\n<blockquote>\n  <p><em>1.&nbsp;&nbsp;Is it possible to capture Python interpreter\'s output from a Python\n  script?</em></p>\n</blockquote>\n\n<p>The answer is "<em>yes</em>", and personally I like the following lifted from the examples in the <em><a href="http://www.python.org/dev/peps/pep-0343/" rel="nofollow noreferrer">PEP 343 -- The "with" Statement</a></em> document.</p>\n\n<pre><code>from contextlib import contextmanager\nimport sys\n\n@contextmanager\ndef stdout_redirected(new_stdout):\n    saved_stdout = sys.stdout\n    sys.stdout = new_stdout\n    try:\n        yield None\n    finally:\n        sys.stdout.close()\n        sys.stdout = saved_stdout\n</code></pre>\n\n<p>And used like this:</p>\n\n<pre><code>with stdout_redirected(open("filename.txt", "w")):\n    print "Hello world"\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>with stdout_redirected(open("filename.txt", "w")):\n    print "Hello world"\n\nprint "screen only output again"\n\nwith stdout_redirected(open("filename.txt", "a")):\n    print "Hello world2"\n</code></pre>\n\n<p>Of course, the above could also be extended to also redirect <code>sys.stderr</code> to the same or another file. Also see this <a href="https://stackoverflow.com/a/16571630/355230">answer</a> to a related question.</p>\n'}]
['https://Stackoverflow.com/questions/24931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1670/']