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.
Asked
Active
Viewed 226 times
0
-
When code do you have so far? You're just reformatting the output from `ps` correct? Is this a duplicate of http://stackoverflow.com/questions/682446/splitting-out-the-output-of-ps-using-python? – S.Lott Oct 14 '10 at 00:12
-
No, but I'll check this post, could turn out to be useful.Thank you. – Vidi Oct 14 '10 at 00:21
1 Answers
2
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
- 842,883
- 184
- 1,785
- 1,677