title: Python subprocess -- close Django server and Docker container with Ctrl-C, return to terminal
body: <p>I'm trying to figure out how to properly close out my script that's supposed to start up a Django server running in a docker container (boot2docker, on Mac OS X). Here's the pertinent code block:</p>
  
  <pre><code>try:
      init_code = subprocess.check_output('./initdocker.sh', shell=True)
      subprocess.call('./startdockerdjango.sh', shell=True)
  except subprocess.CalledProcessError:
      try:
          subprocess.call('./startdockerdjango.sh', shell=True)
      except KeyboardInterrupt:
          return
  </code></pre>
  
  <p>Where <code>startdockerdjango.sh</code> takes care of setting the environment variables that docker needs and starts the server up. The script overall is supposed to know whether to do first-time setup and initialization or simply start the container and server; catching the CalledProcessError means that first time setup was already done and that the container and server can just be started up. The startup works fine, but when a user presses Ctrl-C to stop the server, the server stops normally but then apparently the process that started the server is still going. If I press return, then I can go back to the normal terminal command prompt. If I do any sort of shell command, like <code>ls</code>, then it will be carried out and then I can return to the terminal. I want to change the code so that, if a user presses Ctrl-C, then the server and the container that the server is running in will stop normally and then, afterward, stop the process and have the whole script exit. How can this be done? I don't want to just kill or terminate the process upon KeyboardInterrupt, since then the server and container won't be able to stop normally but will be killed off abruptly. </p>
  
  <p><strong>UPDATE:</strong>
  I recently tried the following according to Padraic Cunningham's comment:</p>
  
  <pre><code>try:
      init_code = subprocess.check_output('./initdocker.sh', shell=True)
      subprocess.call('./startdockerdjango.sh', shell=True)
  except subprocess.CalledProcessError:
      try:
          startproc = subprocess.Popen('./startdockerdjango.sh')
      except KeyboardInterrupt:
          startproc.send_signal(SIGTERM)
          startproc.wait()
          return
  </code></pre>
  
  <p>This was my attempt to send a term to the server to shut down gracefully and then use wait() to wait for the process (<code>startproc</code>) to complete. This, however, results in just having the container and server end abruptly, something that I was trying to prevent. The same thing happens if I try SIGINT instead. What, if anything, am I doing wrong in this second approach? I still want the same overall thing as before, which is having one single Ctrl-C end the container and server, then exit the script. </p>