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?
You could use subprocess.check_output to have a look at your output.
Try this code:
Hope this helped!
Doing the
As suggested by the main answer, is the recommended way and the simplest way to check if a process running. (and it works in jython as well)
If you do not have the process instance in hand to check it. Then use the operating system TaskList / Ps processes.
On windows, my command will look as follows:
This is essentially doing the same thing as the following command line:
And on linux, I do exactly the same using the:
The ps command will already be returning error code 0 / 1 depending on whether the process is found. While on windows you need the find string command.
This is the same approach that is discussed on the followig stack overflow thread:
Verify if a process is running using its PID in JAVA
NOTE: If you use this approach, remeber to wrap your command call in
try: foundRunningProcess = subprocess.check_output(argumentsArray, **kwargs) return True except Exception as err: return False
Note, be careful if you are developing with VS Code and using pure Python and Jython. On my environment, I was under the illusion that the poll() method did not work because a process that I suspected that must have ended was indeed running. This process had launched Wildfly. And after I had asked for wildfly to stop, the shell was still waiting for user to "Press any key to continue . . .".
In order to finish off this process, in pure python the following code was working:
On jython, I had to fix this code to look as follows:
And with this difference the process did indeed finish. And the jython.poll() started telling me that the process is indeed finished.
You can do it for instance:
Python » 3.6.1 Documentation popen-objects
Tested with Python:3.4.2