Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Using popen poll on background process

Tags:

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.

like image 371
Code Slinger Avatar asked Aug 21 '12 15:08

Code Slinger


People also ask

How do I run a Python subprocess in the background?

import os pid = os. fork() if pid == 0: Continue to other code ... This will make the python process run in background. Save this answer.

How do I use Popen in Python?

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.

What is the difference between subprocess run and Popen?

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.

Does subprocess Popen wait for completion?

Save this answer. Try subprocess. call instead of Popen. It waits for the command to complete.


1 Answers

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) 
like image 71
dbr Avatar answered Oct 08 '22 07:10

dbr