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

来源:互联网 发布:诗词翻译赏析软件 编辑:程序博客网 时间:2024/06/06 13:15

问题:解决如何在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 listwith open('top_info.txt', 'r') as f:    lines = f.readlines()print(len(lines))print("initialize arrays:")lines_len = len(lines) - 7       #info need to processcols_name = [i for i in lines[6].split()]arrays = [[0 for i in lines[6].split()] for i in range(lines_len)]                #initialize matrixprint(cols_name)print(len(arrays))print(*arrays, sep='\n')   #print element in multi lines

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

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

#gets into needs to processfor 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 itemgetterprint("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 itemgetterlines = []#read txt file line by line and stored in listwith 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 processarrays = [[0 for i in lines[6].split()] for i in range(lines_len)]#gets into needs to processfor 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

0 0
原创粉丝点击