python 按照cpu的使用率对top中的进程排序(排序表格)

问题:解决如何在python中对表格(二维)进行排序?例如,按照cpu或mem的使用率对top中的进程排序

解决方法:
1. 使用numpy或者panda中的方法对二维矩阵进行操作
2. 使用二维数组(list)存储表格,然后按照某一列排序

下面实现方法二
假设top信息存在于与脚本同目录的txt文件中。具体信息如下:
这里写图片描述

step1:将文本内容读入list存放

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

lines = []
#read txt file line by line and stored in list
with open('top_info.txt', 'r') as f:
    lines = f.readlines()

print(len(lines))


print("initialize arrays:")
lines_len = len(lines) - 7       #info need to process
cols_name = [i for i in lines[6].split()]
arrays = [[0 for i in lines[6].split()] for i in range(lines_len)]                #initialize matrix

print(cols_name)
print(len(arrays))
print(*arrays, sep='\n')   #print element in multi lines

运行结果:
这里写图片描述

step2 : 将要处理的几行信息单独存储

#gets into needs to process
for i in range(7, len(lines)):
    arrays[i-7] = lines[i].split()

print(arrays[0])
print(arrays[1])
print(arrays[2])

运行结果:
这里写图片描述

step3 : 按照cpu和mem的使用率排序,降序

关键代码:

from operator import itemgetter

print("sort info:")
#cpu_row = [row[8] for row in arrays]
arrays_sorted_by_cpu = sorted(arrays, key=itemgetter(8), reverse = True)
print(*arrays_sorted_by_cpu, sep='\n')

运行结果:
这里写图片描述

完整代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from operator import itemgetter

lines = []
#read txt file line by line and stored in list
with open('top_info.txt', 'r') as f:
    lines = f.readlines()

print("the top info in doc is: \n")
print(*lines, sep='\n')

lines_len = len(lines) - 7       #info need to process
arrays = [[0 for i in lines[6].split()] for i in range(lines_len)]

#gets into needs to process
for i in range(7, len(lines)):
    arrays[i-7] = lines[i].split()

print("sort info:")
arrays_sorted_by_cpu = sorted(arrays, key=itemgetter(8), reverse = True)
print(*arrays_sorted_by_cpu, sep='\n')

运行结果:
这里写图片描述


推荐阅读:
知乎:python二维数组按照某一列进行筛选统计?

http://stackoverflow.com/questions/32400639/python-readline

http://stackoverflow.com/questions/5212870/sorting-a-python-list-by-two-criteria

http://stackoverflow.com/questions/4233476/sort-a-list-by-multiple-attributes

http://stackoverflow.com/questions/20183069/how-to-sort-multidimensional-array-by-column

http://stackoverflow.com/questions/2173797/how-to-sort-2d-array-by-row-in-python

http://stackoverflow.com/questions/8609737/python-comparing-two-massive-sets-of-data-in-the-most-efficient-method-possible

http://stackoverflow.com/questions/4183506/python-list-sort-in-descending-order

http://stackoverflow.com/questions/16326529/python-get-process-names-cpu-mem-usage-and-peak-mem-usage-in-windows

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值