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.
The easiest way of running a python script to run in the background is to use cronjob feature (in macOS and Linux). In windows, we can use Windows Task Scheduler. You can then give the path of your python script file to run at a specific time by giving the time particulars.
To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.
Most of your interaction with the Python subprocess module will be via the run() function. This blocking function will start a process and wait until the new process exits before moving on. The documentation recommends using run() for all cases that it can handle.
wait() method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status). If you use this method, you'll prevent that the process zombies are lying around for too long. (Alternatively, you can use subprocess. call() or subprocess.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With