如何根据运行的进程数来打印linux发行版上的前10名用户?我已经成功地使用shell脚本实现了这一点,但现在我对如何使用Python来实现这一点很感兴趣。
发布于 2010-10-14 09:05:02
解析ps aux的输出并不是很令人愉快,而且可能很棘手,因为不能保证格式在所有的Linux系统上都是相同的。
安装像psutil或PSI这样的第三方工具应该会让事情变得简单和可移植。
如果您正在寻找不安装第三方模块的纯Linux解决方案,则以下内容可能会有所帮助:
在现代的Linux系统中,所有进程都按其pid在/procs目录中列出。目录的所有者就是进程的所有者。
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])))收益率
('root', 130)
('unutbu', 55)
('www-data', 7)
('avahi', 2)
('haldaemon', 2)
('daemon', 1)
('messagebus', 1)
('syslog', 1)
('Debian-exim', 1)
('mysql', 1)https://stackoverflow.com/questions/3928959
复制相似问题