문제

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.

도움이 되었습니까?

해결책

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...'
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top