Is there a way to check if a subprocess is still running?

ahura picture ahura · Apr 7, 2017 · Viewed 65.9k times · Source

I'm launching a number of subprocesses with subprocess.Popen in Python. I'd like to check whether one such process has completed. I've found two ways of checking the status of a subprocess, but both seem to force the process to complete. One is using process.communicate() and printing the returncode, as explained here. Another is simply calling process.wait() and checking that it returns 0.

Is there a way to check if a process is still running without waiting for it to complete if it is?

Answer

stovfl picture stovfl · Apr 7, 2017

Ouestion: ... a way to check if a process is still running ...

You can do it for instance:

p = subprocess.Popen(...
"""
A None value indicates that the process hasn't terminated yet.
"""
poll = p.poll()
if poll == None:
  # p.subprocess is alive

Python » 3.6.1 Documentation popen-objects

Tested with Python:3.4.2