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.
There is no portable way to do so using subprocess, you could use another package in combination with it, you can check the https://github.com/dvarrazzo/py-setproctitle library.
Using that module you can name a process title, and then access to it and print the desired output easily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With