Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add process_iter(attrs, ad_value) parameters to retrieve multiple info in one shot #1025

Closed
giampaolo opened this issue Apr 26, 2017 · 0 comments

Comments

@giampaolo
Copy link
Owner

giampaolo commented Apr 26, 2017

Right now the designated way to iterate over all process and query them is:

>>> import psutil
>>> for proc in psutil.process_iter():
...     try:
...         pinfo = proc.as_dict(attrs=['pid', 'name'])
...     except psutil.NoSuchProcess:
...         pass
...     else:
...         print(pinfo)
...
{'pid': 1, 'name': 'systemd'}
{'pid': 2, 'name': 'kthreadd'}
{'pid': 3, 'name': 'ksoftirqd/0'}
...

This is a bit verbose though and requires a try/except. Also it's a bit error prone (race condition) as the user may forget to catch NoSuchProcess.
Proposal is to introduce 2 new parameters, attrs and ad_value, which will be passed to Process.as_dict().
When attrs is specified Process.as_dict() is called and the resulting dict is stored as a info attribute which is attached to the returned Process instance:

>>> import psutil
>>> for proc in psutil.process_iter(attrs=['pid', 'name']):
...     print(proc.info)
...
{'pid': 1, 'name': 'systemd'}
{'pid': 2, 'name': 'kthreadd'}
{'pid': 3, 'name': 'ksoftirqd/0'}

To retrieve all process info attrs=[] shall be #passed.
This also introduces the possibility to use list/dict comprehensions:

>>> procs = [p for p in psutil.process_iter(attrs=['pid', 'name', 'username'])]
>>> procs
[<psutil.Process(pid=1, name='systemd') at 140154039741328>,
 <psutil.Process(pid=2, name='kthreadd') at 140154039742416>,
 <psutil.Process(pid=3, name='ksoftirqd/0') at 140154039804560>,
 ...]
>>>
>>> info = dict([(p.pid, p.info) for p in procs])
>>> info
{1: {'name': 'systemd', 'pid': 1, 'username': 'root'},
 2: {'name': 'kthreadd', 'pid': 2, 'username': 'root'},
 3: {'name': 'ksoftirqd/0', 'pid': 3, 'username': 'root'},
 ...}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant