0

I have a list of commands that I iterate through

lst = ['commandone', 'commandtwo', 'commandthree']

for command in lst:
    subprocess.run(command)

Does anyone know specifically how subprocess handles these commands when passed in a loop like this? Do they execute simultaneously or does the subprocess module wait on each command to finish before the other begins? What would be the best way to determine this?

codingInMyBasement
  • 728
  • 1
  • 6
  • 20
  • 1
    `subprocess.run` is synchronous: it waits for a command to exit. If you don't want that, use `subprocess.Popen` instead. – Charles Duffy Oct 07 '22 at 21:20
  • popen runs them asynchronously? – codingInMyBasement Oct 07 '22 at 21:26
  • 1
    Correct, Popen does not wait. If that's what you want, consider something like `processes = [subprocess.Popen(cmd) for cmd in lst]` -- that way you have a handle for each process you can use to check their status. – Charles Duffy Oct 07 '22 at 21:27
  • 1
    Also, note that it's better practice to pass `Popen` an array. As it is, your code will only work if your commands take no arguments (or if you add `shell=True`, but that's a bad idea). So better form is something like `lst = [ ['commandone', 'arg1'], ['commandtwo', 'arg2'], ['commandthree', 'arg3'] ]` – Charles Duffy Oct 07 '22 at 21:28

0 Answers0