This script gets system data from Linux top command: load averages, number of users, and top processes' PID, USER, CPU%, and Command Path. url is also here.
I am kinda hoping someone might chime in...
In the client of the script... is there a better way to print the key/value pairs from a generator object?
I tried the usual .items() method and the iter() keyword but didn't work:
#! /usr/bin/python3
from os import popen
import pprint
class Top:
def __init__(self):
self.general_sys_info = {
'number_of_users': '',
'load_averages': []
}
self.process = {
'pid': '',
'user': '',
'cpu_percentage': '',
'command_path': ''
}
def __start_process(self):
for line in popen('top -n 1 -bc | head -15'):
if len(line.split()) != 0:
yield line.split()
def run_top(self):
first_elements = ['Tasks:', '%Cpu(s):', 'KiB', 'PID']
for line_list in self.__start_process():
if line_list[0] not in first_elements:
if line_list[0] != 'top':
self.process['pid'] = line_list[0]
self.process['user'] = line_list[1]
self.process['cpu_percentage'] = line_list[8]
self.process['command_path'] = ' '.join(line_list[11:])
yield self.process
else:
self.general_sys_info['number_of_users'] = line_list[5]
self.general_sys_info['load_averages'] = line_list[9:12]
yield self.general_sys_info
if __name__ == "__main__":
pp = pprint.PrettyPrinter(indent=4)
for system_info in Top().run_top():
pp.pprint(system_info)
print('\n')I am kinda hoping someone might chime in...
In the client of the script... is there a better way to print the key/value pairs from a generator object?
I tried the usual .items() method and the iter() keyword but didn't work:
for k,v in Top().run_top().items():
print(k)
print(v)and...for k,v in iter(Top().run_top().items()):
print(k)
print(v)Not much luck though
