1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| import threading import time
from psutil import cpu_percent, virtual_memory from pystray import Icon, Menu, MenuItem
class ICOImage: def __init__(self, path: str): with open(path, 'rb') as file: self._data = file.read() def save(self, file, format): file.write(self._data)
def thread_get_usage(): global cpu_usage, mem_usage while True: if thread_flag: break cpu_usage = cpu_percent(interval=1) / 100 mem_usage = virtual_memory().percent / 100 time.sleep(0.5)
def changeMonitor(new_monitor): global monitor print(monitor, new_monitor) if new_monitor != monitor: monitor = new_monitor
def on_quit(): global thread_flag thread_flag = 1 runcat.stop()
monitor = 'CPU' cpu_usage = 0.2 mem_usage = 0.2 cats = [ICOImage(f'icons/runcat/{i}.ico') for i in range(5)]
menu = (MenuItem(text='CPU', action=lambda: changeMonitor('cpu')), MenuItem(text='MEM', action=lambda: changeMonitor('mem')), MenuItem(text='QUIT', action=on_quit)) runcat = Icon('run cat', icon=cats[0], title='run cat', menu=menu)
thread_flag = 0 threading.Thread(target=runcat.run).start() threading.Thread(target=thread_get_usage).start()
while True: if thread_flag: break for icon in cats: runcat.icon = icon mon = mem_usage if monitor == 'mem' else cpu_usage t = 0.2 - mon * 0.15 print(f'{mon=:.2%}, {t=:.2f}s, {cpu_usage=:.2%}, {mem_usage=:.2%}')
tip = f'cpu: {cpu_usage:.2%} \nmem: {mem_usage:.2%}' runcat.title = tip
time.sleep(t)
|