diff --git a/color-top.py b/color-top.py index f52769b..33073fd 100644 --- a/color-top.py +++ b/color-top.py @@ -14,11 +14,15 @@ import argparse import tty import termios -GREEN = "\033[32m" -YELLOW = "\033[33m" -ORANGE = "\033[38;5;214m" -RED = "\033[31m" -RESET_TO_GREEN = "\033[32m" +def supports_color(): + if not sys.stdout.isatty(): + return False + term = os.environ.get('TERM', '') + if 'color' in term.lower(): + return True + if os.name == 'nt': + return True + return False def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') @@ -43,25 +47,32 @@ def get_top_processes(limit): processes.sort(reverse=True, key=lambda p: p[0]) return processes[:limit] -def colorize(cpu, name, user): - if cpu <= 25: +def colorize(cpu, name, user, use_color): + if cpu <= 25 or not use_color: return f"{cpu:6.2f}% {name[:25]:<25} {user[:15]:<15}" else: + YELLOW = "\033[33m" + ORANGE = "\033[38;5;214m" + RED = "\033[31m" + RESET_TO_GREEN = "\033[32m" color = YELLOW if cpu <= 50 else ORANGE if cpu <= 75 else RED cpu_str = f"{cpu:6.2f}%" return f"{color}{cpu_str} {name[:25]:<25} {user[:15]:<15}{RESET_TO_GREEN}" -def print_processes(limit, show_quit_hint=True): +def print_processes(limit, show_quit_hint=True, use_color=True): clear_screen() top_processes = get_top_processes(limit) - print(GREEN, end='') + GREEN = "\033[32m" if use_color else "" + + if use_color: + print(GREEN, end='') print(" CPU Process User") print("----------------------------------------------") for (cpu, name, user) in top_processes: - print(colorize(cpu, name, user)) + print(colorize(cpu, name, user, use_color)) if show_quit_hint: print("\nPress 'q' to quit.") @@ -81,10 +92,13 @@ 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).") parser.add_argument("-i", "--interval", type=int, default=1, help="Refresh interval in seconds (default is 1).") + parser.add_argument("--no-color", action="store_true", help="Disable colored output.") args = parser.parse_args() limit = args.number interval = max(1, args.interval) + use_color = not args.no_color and supports_color() + refresh_count = 0 start_time = time.time() @@ -93,9 +107,10 @@ def main(): refresh_count += 1 elapsed = time.time() - start_time show_quit = refresh_count < 3 and elapsed < 3 - print_processes(limit, show_quit_hint=show_quit) + print_processes(limit, show_quit_hint=show_quit, use_color=use_color) key = wait_for_keypress(timeout=interval) if key and key.lower() == 'q': + print("Exiting...") break except KeyboardInterrupt: print("\nProgram interrupted. Exiting...")