I am using python's subprocess.Popen() to run multiple subprocesses at a time. Each time a process is terminated, I want to print something like this to the shell:
process ABC has been terminated
ABC being a name that I give to the process myself.
I thought maybe there is a way to achieve this using some code like this: process.name()
Is there a way to do that through subprocess.Popen()?
This is a textbook example of what you use inheritance for.
import subprocess
class NamedPopen(subprocess.Popen):
"""
Like subprocess.Popen, but returns an object with a .name member
"""
def __init__(self, *args, name=None, **kwargs):
self.name = name
super().__init__(*args, **kwargs)
fred = NamedPopen('sleep 11; echo "yabba dabba doo"', shell=True, name="fred")
barney = NamedPopen('sleep 22; echo "hee hee, okay fred"', name="barney", shell=True)
print('... stay tuned ...')
fred.wait()
barney.wait()
Just take care to not pick an attribute name which the parent class uses for something else.