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>your script is in fact working as intended. You likely are expecting a traceback to be printed to stderr of your subprocess, but that's not how <code>sys.exit()</code> works.</p>

<h3>script1.py</h3>

<pre class="lang-python prettyprint-override"><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[::-1] #prints reversed message proving print is called from script1 not script2
    print error #prints nothing because there is no error text (no error was raised only system exit)
    print 'return status: '+str(proc.returncode) #this is what sys.exit() modifies
func1()
print "Done.. YAY" #done prints after call</code></pre>

<h3>script2.py</h3>

<pre class="lang-python prettyprint-override"><code>import sys
print "ERROR:port not detected"
sys.exit(29) #does not print traceback (or anything) only sets return code
print "Done.." #never prints because python interpreter is terminated</code></pre>

<p>when script1 calls script2 as a subprocess, script2 prints it's first statement to the stdout pipe, then exits with a return code of 29. A system exit with a return code of 0 is viewed as a successful return, so unless you specifically call something that raises an error, nothing will print to the stderr pipe. the return code can however be determined from the attribute <code>returncode</code> of your <code>proc</code>.</p>

<p>running <code>&gt;python script1.py</code> yields:</p>

<pre>
detceted ton trop:RORRE

return status: 29
Done.. YAY</pre>

python popen