How to capture the prints of a python script being executed from another python script?
<p>I have 2 scripts <code>script1.py</code> and <code>script2.py</code> in the same folder ,script1.py calls script2.py using Popen(See code below for details),issue is that the prints coming from script2.py is not being captured in script1.py,<code>print output</code> and <code>print error</code> doesn't print a thing in the code below? what am I missing here? how do I capture the prints from script2.py?</p>

<p>script1.py</p>

<pre><code>import subprocess
from subprocess import Popen, PIPE, STDOUT
def func1 ():
    cmd = "python script2.py"
    proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
    (output, error) = proc.communicate()
    print output
    print error

func1()
print "Done.."
</code></pre>

<p>script2.py</p>

<pre><code>import sys
print "ERROR:port not detected"
sys.exit(29)
</code></pre>

<p>OUTPUT:-</p>

<pre><code>C:\Dropbox&gt;python script1.py
ERROR:port not detected


Done..
</code></pre>

<p><strong>Edited answer based on comments</strong></p>

<p>Looks like after the edits you made to the original question, Your code is working correctly.
I just put <code>output=</code> in front of print statement to check that.</p>

<pre><code>import subprocess
from subprocess import Popen, PIPE, STDOUT
def func1 ():
    cmd = "python script2.py"
    proc = Popen(cmd.split(' '), stdout=PIPE, stderr=PIPE)
    (output, error) = proc.communicate()
    print "output=",output
    print error

func1()
print "Done.."
</code></pre>

<p>** OUTPUT: **</p>

<pre><code>Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
&gt;&gt;&gt; ================================ RESTART ================================
&gt;&gt;&gt; 
output= ERROR:port not detected



Done..
&gt;&gt;&gt; 
</code></pre>

python popen