此题目涉及到Python对进程的操作、for循环计数循环次数、排序与打印表格等,题目比较简单,效果图如下:
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#!/usr/bin/python # encoding: utf-8 # -*- coding: utf8 -*- """ Created by PyCharm. File: LinuxBashShellScriptForOps:performanceOps.py User: Guodong Create Date: 2016/9/21 Create Time: 18:11 """
import psutil
import prettytable
ps_result = list ()
for proc in psutil.process_iter():
ps_result.append({ 'name' : proc.name(), 'pid' : proc.pid, 'cpu_percent' : proc.cpu_percent(),
'memory_percent' : proc.memory_percent()})
table = prettytable.PrettyTable()
table.field_names = [ "No." , "Name" , "pid" , "Memory percent" ]
for i, item in enumerate ( sorted (ps_result, key = lambda x: x[ 'memory_percent' ], reverse = True )):
table.add_row([i + 1 , item[ 'name' ], item[ 'pid' ], format (item[ 'memory_percent' ] / 100 , '.2%' )])
if i > = 9 :
break
print table
|
代码也可以从GitHub上获取,https://github.com/DingGuodong/LinuxBashShellScriptForOps/blob/master/functions/process/performanceOps.py
其中用到了两个主要的第三方模块,psutil(用于获取进程信息)和prettytable(用于打印表格),Windows和Linux系统上均可使用,如果提示“ImportError: No module named xxxx”,则可以执行命令pip install xxxx或者easy_install xxxx。
--end--
本文转自 urey_pp 51CTO博客,原文链接:http://blog.51cto.com/dgd2010/1855467,如需转载请自行联系原作者