Return code of a bash script being called from a Subprocess
<p>I am writing a script that imports a bunch of data to a couchdb database, the issue is each db takes around 15 minutes, so I do not watch the whole thing as I have on average 20 db to import.</p>

<p>The script loops through an array of items, and then calls subprocess on each in order run the import before moving on to the next.</p>

<p>What I have tried to do is catch any db's that do not load correctly, by way of failed script.
I am trying to catch this when the return code is not 0, the issue is I can only get the return code of the subprocess calling the docker command, not if the script executes correctly. </p>

<pre><code>#!/usr/bin/python
import sys
import subprocess

cities = ["x","y", "z"];

uncompletedcities = []
for x in cities:
    dockerscript = "docker exec -it docker_1 ./node_modules/.bin/babel-node --debug --presets es2015 app/exportToCouch %s %s" % (x,x)
    p = subprocess.Popen(dockerscript, shell=True, stderr=subprocess.PIPE)
    error = p.communicate()
    if p.returncode != 0:
            uncompletedcities.append(x)

    while p.poll() == None:
        print p.stderr.read()

print (uncompletedcities)
</code></pre>

<p>so the issue is, I recieve the return code of </p>

<pre><code>p = subprocess.Popen(dockerscript, shell=True, stderr=subprocess.PIPE)
</code></pre>

<p>not the return code of the script being called here</p>

<pre><code>dockerscript = "docker exec -it docker_1 ./node_modules/.bin/babel-node --debug --presets es2015 app/exportToCouch %s %s" % (x,x)
</code></pre>

<p>so in essence, I want to go one deeper into the return code, and get the return code of the docker command that subprocess is calling, no the return code of subprocess. </p>

<p>So just to get the return code of this:</p>

<pre><code>docker exec -it docker_1 ./node_modules/.bin/babel-node --debug --presets es2015 app/exportToCouch 
</code></pre>

<p>Note that when you run:</p>

<pre><code>docker exec -it
</code></pre>

<p>your <code>-it</code> flags are doing something contrary to the point of what you are trying. You are trying to open an interactive session. This isn't actually <em>executing</em> the command.</p>

<p>You can remove both of these from your command and just run <code>docker exec</code>:</p>

<pre><code>dockerscript = "docker exec docker_1 ./node_modules/.bin/babel-node --debug --presets es2015 app/exportToCouch %s %s" % (x,x)
</code></pre>

<p>For what it's worth I would probably look into using <a href="https://github.com/docker/docker-py" rel="nofollow">docker-py</a>, too. It's a lot more flexible for running docker commands if you end up with more than just a few command line docker commands. It also lets you avoid <code>shell=true</code>.</p>

python bash docker