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
.
import os pid = os. fork() if pid == 0: Continue to other code ... This will make the python process run in background. Save this answer.
Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as in open() function.
The main difference is that subprocess. run() executes a command and waits for it to finish, while with subprocess. Popen you can continue doing your stuff while the process finishes and then just repeatedly call Popen. communicate() yourself to pass and receive data to your process.
Save this answer. Try subprocess. call instead of Popen. It waits for the command to complete.
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)
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