Python Forum
Getting wanted data from the 'top' command (Linux)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Getting wanted data from the 'top' command (Linux)
#4
forgot to post the completed version:

#! /usr/bin/python3
# get system data from top: load averages, number of users,
# and top processes' PID, USER, CPU%, and Command Path
from os import popen
from itertools import chain


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__":
    for k, v in enumerate(chain.from_iterable(i.items() for i in Top().run_top())):
        if k < 2 or 'command_path' in v:
            print("%s: %s\n" % (v[0],  v[1]))
        else:
            print("%s: %s" % (v[0], v[1]))
Reply


Messages In This Thread
RE: Getting wanted data from the 'top' command (Linux) - by rootVIII - Nov-16-2018, 05:08 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Command output to pdf (linux) Gribouillis 0 5,016 Mar-05-2021, 07:35 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020