简体   繁体   中英

How to run Python's subprocess and leave it in background

I have seen A LOT of posts regarding my topic, but actually I didn't find a solution for my problem. I'm trying to run a subprocess in a background, without wait for subprocess execution. The called subprocess is a shell script, which does a lot of different things. This is a small piece of my code:

print "Execute command:", full_command
subprocess.Popen(full_command, stdin=None, stdout=None, stderr=None, close_fds=True).communicate()
print "After subprocess"

And my problem is that Python waits until subprocess.Popen finishes it's job. I read, that stdin(-out, -err)=None should solve this problem, but it's not. Also close_fds=True, doesn't help here.

From the Popen.communicate documentation (emphasis mine):

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

If you don't want to wait for the process to terminate, then simply don't call communicate :

subprocess.Popen(full_command, close_fds=True)

Might be another way of doing it, with the optional capability to inspect the subprocess output for a while, from github.com/hologram-io/hologram-python pppd.py file:

    self.proc = Popen(self._commands, stdout=PIPE, stderr=STDOUT)

    # set stdout to non-blocking
    fd = self.proc.stdout.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM