How to capture Python interpreter's and/or CMD.EXE's output from a Python script?
<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>

<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>

<pre><code>python script_a.py | python script_b.py
</code></pre>

<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">standard streams</a> on Wikipedia.</p>

<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>

<pre><code>import subprocess
# Of course you can open things other than python here :)
process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
x = process.stderr.readline()
y = process.stdout.readline()
process.wait()
</code></pre>

<p>See the Python <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow">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">file objects</a>.</p>

<p>For use with pipes, reading from standard input as <a href="http://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939" rel="nofollow">lassevk</a> suggested you'd do something like this:</p>

<pre><code>import sys
x = sys.stderr.readline()
y = sys.stdin.readline()
</code></pre>

<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">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">pipes</a> module.</p>

<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">polling</a> which unfortunately does not work in windows, but I'm sure there's some alternative out there.</p>
