Python: Using popen poll on background process

Code Slinger picture Code Slinger · Aug 21, 2012 · Viewed 52.8k times · Source

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.

Answer

dbr picture dbr · Aug 21, 2012

You don't need to use the shell backgrounding & syntax, as subprocess will run the process in the background by itself

Just run the command normally, then wait until Popen.poll returns not None

import time
import subprocess

p = subprocess.Popen("sleep 30", shell=True)
# Better: p = subprocess.Popen(["sleep", "30"])

# Wait until process terminates
while p.poll() is None:
    time.sleep(0.5)

# It's done
print("Process ended, ret code:", p.returncode)