From da58b4374cdc45c5d5a6186b78534b1e32fce4de Mon Sep 17 00:00:00 2001 From: JustinOros Date: Thu, 31 Jul 2025 14:08:27 -0700 Subject: [PATCH] Revised output for a cleaner look. --- color-top.py | 55 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/color-top.py b/color-top.py index bd20875..cfc5895 100644 --- a/color-top.py +++ b/color-top.py @@ -11,6 +11,8 @@ import sys import select import socket import argparse +import tty +import termios GREEN = "\033[32m" YELLOW = "\033[33m" @@ -18,7 +20,19 @@ ORANGE = "\033[38;5;214m" RED = "\033[31m" RESET = "\033[0m" +def clear_screen(): + os.system('cls' if os.name == 'nt' else 'clear') + def get_top_processes(limit): + # Prime cpu_percent readings + for proc in psutil.process_iter(['pid']): + try: + proc.cpu_percent(interval=None) + except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): + continue + + time.sleep(0.1) + processes = [] for proc in psutil.process_iter(['cpu_percent', 'name', 'username']): try: @@ -32,38 +46,45 @@ def get_top_processes(limit): def colorize(cpu, name, user): color = GREEN if cpu <= 25 else YELLOW if cpu <= 50 else ORANGE if cpu <= 75 else RED - cpu_str = f"{cpu:.2f}%" # Displaying CPU usage with 2 decimal places - return f"{color}{cpu_str}, {name}, {user}{RESET}" + cpu_str = f"{cpu:6.2f}%" + return f"{color}{cpu_str} {name[:25]:<25} {user[:15]:<15}{RESET}" def print_processes(limit): - os.system('clear') + clear_screen() top_processes = get_top_processes(limit) - hostname = socket.gethostname() - header = f"Top {limit} Running Processes ({hostname}):" - print(header) - print("-" * len(header)) + print("CPU % Process Name User") + print("----------------------------------------------") - for idx, (cpu, name, user) in enumerate(top_processes, start=1): + for (cpu, name, user) in top_processes: print(colorize(cpu, name, user)) + print("\nPress 'q' to quit.") + +def wait_for_keypress(timeout=1.0): + fd = sys.stdin.fileno() + old_settings = termios.tcgetattr(fd) + try: + tty.setcbreak(fd) + if select.select([sys.stdin], [], [], timeout)[0]: + return sys.stdin.read(1) + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) + return None + def main(): parser = argparse.ArgumentParser(description="Monitor system processes by CPU usage.") parser.add_argument("-n", "--number", type=int, default=10, help="Number of processes to monitor (default is 10).") - args = parser.parse_args() limit = args.number - + try: while True: print_processes(limit) - time.sleep(1) - - if sys.stdin in select.select([sys.stdin], [], [], 0)[0]: - input_char = sys.stdin.read(1) - if input_char.lower() == 'q': - print("Exiting...") - break + key = wait_for_keypress(timeout=1.0) + if key and key.lower() == 'q': + print("Exiting...") + break except KeyboardInterrupt: print("\nProgram interrupted. Exiting...")