python 按照cpu的使用率對top中的程序排序(排序表格)
阿新 • • 發佈:2019-01-26
問題:解決如何在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')
執行結果: