4

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
4

2 回答 2

6

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'
于 2012-06-12T01:40:01.937 回答
4

As mentioned by Lattyware, If you're making the Popen call yourself, you can just save it then to retrieve later. You don't actually need a container class to use do this, as you can just store it in the instance's internal dict:

>>> import subprocess
>>> 
>>> to_exec = 'ls'
>>> p = subprocess.Popen(to_exec)
>>> p.name = to_exec

and then later:

>>> p.name
'ls'
>>> 
于 2012-06-12T01:43:17.047 回答