Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: get command name of Popen instance

I have an instance of the Popen class created through subprocess.Popen. I would like to get the name of that process, but I can't find any method or instance variable that would let me get at that. For example, if I had:

p = subprocess.Popen('ls')

I would like to find a method to give me the name of the process, something that would work like:

>>> p.name()
ls
like image 565
troyastorino Avatar asked Dec 27 '22 23:12

troyastorino


1 Answers

The answer is no, until the latest versions of Python (non-stable).

Looking at the source for 3.2.3, you can see that information isn't stored in the object (it is discarded). However, in the latest development version of Python, it has been added as subprocess.Popen.args.

So, presuming this makes it into 3.3, the only time you will see this as a feature is then. The development docs don't mention it, but that could just be them not being updated. The fact that it's not prefixed with an underscore (_args) implies that it is intended to be a public attribute.

If you are desperate to do this as part of the object, the easiest answer is simply to subclass subprocess.Popen() and add the data yourself. That said, I really don't think it's worth the effort in most cases.

>>> class NamedPopen(Popen):
...     def __init__(self, cargs, *args):
...         Popen.__init__(self, cargs, *args)
...         self.args = cargs
... 
>>> x = NamedPopen("ls")
>>> x.args
'ls'
like image 158
Gareth Latty Avatar answered Jan 15 '23 18:01

Gareth Latty