I am running a long process (actually another python script) in the background. I need to know when it has finished. I have found that Popen.poll()
always returns 0 for a background process. Is there another way to do this?
p = subprocess.Popen("sleep 30 &", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
a = p.poll()
print(a)
Above code never prints None
.
You don't need to use the shell backgrounding
&
syntax, assubprocess
will run the process in the background by itselfJust run the command normally, then wait until
Popen.poll
returnsnot None
You shouldn't run your script with ampersand at the end. Because shell forks your process and returns 0 exit code.
I think you want either the
popen.wait()
orpopen.communicate()
commands. Communicate will grab thestdout
andstderr
data which you've put intoPIPE
. If the other item is a Python script I would avoid running ashell=True
call by doing something like:Of course these hold the main thread and wait for the other process to complete, which might be bad. If you want to busy wait then you could simply wrap your original code in a loop. (Your original code did print "None" for me, btw)
Example of the wrapping in a loop solution: