Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name process when creating it with python's subprocess.Popen()

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()?

like image 598
Sky Avatar asked Oct 21 '25 01:10

Sky


2 Answers

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.

like image 109
tripleee Avatar answered Oct 23 '25 15:10

tripleee


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.

like image 31
David Avatar answered Oct 23 '25 16:10

David