stanleyli stanleyli - 21 days ago 6
Python Question

How to name a subprocess in Python

In Python 2.7, I have a producer which kicks off several subprocesses:

processes.append(subprocess.Popen(command, env=my_env)


I also have a consumer which checks the status of the subprocesses and then do some work:

for proc in processes:
if proc.poll() is not None:
# do some work


I need to assign each subprocess a name when kicking them off so that the consumer can print out something like:"
Subprocess xxx finished!
"

How can I do that?

Answer

You don't make clear what processes is; you say “a producer which kicks off several subprocesses”, but that doesn't tell us what the type is and what it's capable of.

So, when you use processes.append, I'll assume processes is just a sequence with list-like semantics.

Why do they need a name? Processes already get assigned a process ID by the operating system. You can do this:

proc = subprocess.Popen(command, env=my_env)
processes.append(proc)

for proc in processes:
    if proc.poll() is not None:
        # do some work
    else:
        print("Subprocess {proc.pid} finished!".format(proc=proc))