Mark O'Sullivan
Mark O'Sullivan

Reputation: 10768

Wanting to stop subprocesses when all of them have finished running

Currently I'm running a python script which runs all of the shell scripts inside a certain directory. I'm having trouble because the process doesn't stop even when all the other scripts have finished running.

This is my code

for file in dirs:
    if file.endswith(".sh"):
        filePath = os.getcwd() + "/arrayscripts/" + file
        arrayProcess = subprocess.Popen([filePath, delay, loop, userID], shell=False)

Is there any way I can check to see whether or not all of these scripts have finished running and so I can kill arrayProcess?

Previously I tried using the delay and loop variables to find out how long the script would run and then add one second to the result. I then used this result to tell my script to sleep until the script had finished and then kill arrayProcess. Apparently this isn't a good way to go about doing this because there can sometimes be unexpected delays/ lags and so I should be using a different solution.

Upvotes: 0

Views: 47

Answers (1)

Tim Zimmermann
Tim Zimmermann

Reputation: 6420

You can use Popen.wait() to wait for the processes to terminate.
The best option would be to store all the processes in a list and after starting all of them just wait() until they terminate. You should not have to kill them manually (if the scripts exit on their own).

Upvotes: 1

Related Questions