Search code examples
pythonhttp-redirectpidspawndetach

Python: spawn subprocess with several requirements


Using python 2.6 or 2.7, I need to spawn a subprocess:

  • it must be detached
  • it's output must be redirected
  • the spawning python process must print the subprocess's PID, and then exit.

I've gone through the various modules (and various Stackoverflow posts), and it seems all of them conflict with one or more of these requirements. E.g. os.system() = no pid; subprocess.* = either no redirect or no detach.


Solution

  • By detached I assume you mean you want your script to continue running after you start the subprocess, correct? If so, I believe you'll have to fork, start the subprocess in the child process and capture it's output there.

    import os
    import subprocess
    
    cmd = 'ls'
    
    if os.fork() == 0:
            process = subprocess.Popen(cmd, shell=True, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
            print "subprocess pid: %d" % process.pid
            stdout = process.communicate()
            print stdout
    else:
            print 'parent...'