views:

39

answers:

1

How could I print the top 10 users on a linux distribution by the number of processes they have running? I have managed to do this using a shell script, but now I'm interested at how I can do this using Python.

+1  A: 

Parsing the output of ps aux is not very pleasant, and can be tricky because the format is not guaranteed to be the same on all Linux systems.

Installing a third-party tool like psutil or PSI should make things easy and portable.

If you are looking for a Linux-only solution without installing a third-party module, then the following might help:

On modern Linux systems, all processes are listed in the /procs directory by their pid. The owner of the directory is the owner of the process.

import os
import stat
import pwd
import collections
import operator

os.chdir('/proc')
dirnames=(dirname for dirname in os.listdir('.') if dirname.isdigit())
statinfos=(os.stat(dirname) for dirname in dirnames)
uids=(statinfo[stat.ST_UID] for statinfo in statinfos)
names=(pwd.getpwuid(uid).pw_name for uid in uids)
counter=collections.defaultdict(int)
for name in names:
    counter[name]+=1
count=counter.items()
count.sort(key=operator.itemgetter(1),reverse=True)
print('\n'.join(map(str,count[:10])))

yields

('root', 130)
('unutbu', 55)
('www-data', 7)
('avahi', 2)
('haldaemon', 2)
('daemon', 1)
('messagebus', 1)
('syslog', 1)
('Debian-exim', 1)
('mysql', 1)
unutbu
This works well.Thank you!
Vidi