How to run Python's subprocess and leave it in background
Solution 1
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)
Solution 2
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)
mchfrnc
Updated on June 16, 2022Comments
-
mchfrnc almost 2 years
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.