Repository navigation
Expand file tree
/
Copy pathSystemMonitorGadget_Original.py
More file actions
737 lines (607 loc) · 29.3 KB
/
Copy pathSystemMonitorGadget_Original.py
File metadata and controls
737 lines (607 loc) · 29.3 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
import tkinter as tk
from tkinter import ttk
import psutil
import os
import sys
import time
import psutil
import threading
import tkinter as tk
from tkinter import ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import platform
import subprocess
import re
import numpy as np
from collections import deque
# Use dark theme for the application
style.use('dark_background')
def get_network_speed_windows():
"""Get network interface speed using Windows commands with fallback methods"""
try:
# Try getting speed using WMIC first
try:
result = subprocess.check_output(
['wmic', 'nic', 'where', 'NetEnabled=True', 'get', 'Name,Speed,NetConnectionStatus', '/value'],
creationflags=subprocess.CREATE_NO_WINDOW
).decode('utf-8', 'ignore')
# Parse the output to find the first active interface with speed
lines = result.strip().split('\n')
current_name = None
current_status = None
for line in lines:
line = line.strip()
if line.startswith('Name='):
current_name = line.split('=')[1].strip()
elif line.startswith('NetConnectionStatus=') and current_name:
current_status = line.split('=')[1].strip()
elif line.startswith('Speed=') and current_name and current_status == '2': # Status 2 = Connected
speed = line.split('=')[1].strip()
if speed and speed != '0':
return int(speed) / 1_000_000 # Convert to Mbps and return
except Exception:
pass
# Fallback: Try getting speed using PowerShell
try:
ps_command = """Get-NetAdapter | Where-Object { $_.Status -eq 'Up' } |
Select-Object -ExpandProperty LinkSpeed -First 1 |
ForEach-Object { if ($_ -match '(\d+)') { [int]$matches[1] } }"""
result = subprocess.check_output(
['powershell', '-Command', ps_command],
creationflags=subprocess.CREATE_NO_WINDOW
).decode('utf-8').strip()
if result and result.isdigit():
return int(result)
except Exception:
pass
# Fallback: Common network speeds based on interface type
try:
# Check if this is a WiFi interface
result = subprocess.check_output(
['netsh', 'wlan', 'show', 'interfaces'],
creationflags=subprocess.CREATE_NO_WINDOW
).decode('utf-8', 'ignore')
if 'Wi-Fi' in result or 'Wireless' in result:
# Common WiFi speeds (Mbps) - return fastest common WiFi speed
return 1000
except Exception:
pass
# Final fallback: Default to 1000 Mbps (1 Gbps)
return 1000
except Exception:
return 1000 # Default to 1 Gbps on error
class SystemMonitor:
def __init__(self, root):
self.root = root
self.root.title("System Monitor")
self.root.overrideredirect(True) # Remove title bar
self.root.resizable(False, False)
# Set theme colors
self.bg_color = "#202020"
self.fg_color = "#ffffff"
self.accent_color = "#0078d4"
self.card_color = "#252525" # Slightly darker for better contrast
# Position window in the upper right corner of screen
screen_width = self.root.winfo_screenwidth()
window_width = 240 # Slightly wider to accommodate process names
window_height = 500 # More compact height
x_position = screen_width - window_width - 10 # 10px from right edge
y_position = 10 # 10px from top
self.root.geometry(f"{window_width}x{window_height}+{x_position}+{y_position}")
self.root.configure(bg=self.bg_color)
# Initialize variables before setting up UI
self.setup_variables()
# Make window draggable
self._drag_data = {"x": 0, "y": 0}
self._make_draggable()
# Add close button
close_btn = tk.Button(self.root, text='×', font=('Arial', 12, 'bold'),
command=self.quit_application,
bg='#ff4444', fg='white',
bd=0, highlightthickness=0, relief='flat',
activebackground='#ff6666', activeforeground='white')
close_btn.place(x=window_width-25, y=2, width=22, height=22)
# Add right-click context menu
self.context_menu = tk.Menu(self.root, tearoff=0, bg='#333333', fg='white',
activebackground='#0078d4', activeforeground='white')
self.context_menu.add_command(label="Exit", command=self.quit_application)
# Bind right-click to show context menu
self.root.bind("<Button-3>", self.show_context_menu)
# Allow other windows to appear on top
self.root.wm_attributes("-topmost", False)
# Bind Escape key to quit
self.root.bind('<Escape>', lambda e: self.quit_application())
# Initialize network speed
self.network_speed_mbps = get_network_speed_windows()
# Setup and start UI
self.setup_ui()
self.monitoring = True
self.start_monitoring()
def _make_draggable(self):
"""Make the window draggable"""
def on_drag_start(event):
self._drag_data["x"] = event.x
self._drag_data["y"] = event.y
def on_drag_motion(event):
x = self.root.winfo_x() + (event.x - self._drag_data["x"])
y = self.root.winfo_y() + (event.y - self._drag_data["y"])
self.root.geometry(f"+{x}+{y}")
# Bind the events to the drag handle
self._drag_handle = tk.Frame(self.root, bg=self.bg_color, height=20, cursor='fleur')
self._drag_handle.pack(fill=tk.X, pady=(0, 3))
self._drag_handle.bind('<Button-1>', on_drag_start)
self._drag_handle.bind('<B1-Motion>', on_drag_motion)
def setup_variables(self):
# Data storage for graphs (last 60 data points)
self.cpu_data = deque(maxlen=60)
self.hdd_data = deque(maxlen=60)
self.network_data = deque(maxlen=60)
# Initialize with zeros
for _ in range(60):
self.cpu_data.append(0)
self.hdd_data.append(0)
self.network_data.append(0)
# Network baseline for calculating usage
self.network_baseline = psutil.net_io_counters()
self.last_network_time = time.time()
def show_context_menu(self, event):
"""Show the context menu"""
try:
self.context_menu.tk_popup(event.x_root, event.y_root)
finally:
self.context_menu.grab_release()
def quit_application(self):
"""Safely quit the application"""
if hasattr(self, 'monitoring'):
self.monitoring = False
if hasattr(self, 'update_job'):
self.root.after_cancel(self.update_job)
self.root.destroy()
def get_top_processes(self, metric='cpu', count=3):
"""Get top processes by resource usage"""
try:
processes = []
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent', 'io_counters', 'username']):
try:
pinfo = proc.info
if metric == 'cpu':
value = pinfo.get('cpu_percent', 0)
elif metric == 'memory':
value = pinfo.get('memory_percent', 0)
elif metric == 'disk':
io = pinfo.get('io_counters', None)
value = io.write_bytes + io.read_bytes if io else 0
else:
continue
name = os.path.splitext(pinfo['name'])[0]
processes.append((name, value, pinfo.get('pid', 0)))
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
# Sort and get top N
processes.sort(key=lambda x: x[1], reverse=True)
return processes[:count]
except Exception as e:
print(f"Error getting top processes: {e}")
return [("Error", 0, 0)] * count
def update_top_processes(self):
"""Update the top processes display"""
try:
# Get top processes for each resource
top_cpu = self.get_top_processes('cpu', 3)
top_mem = self.get_top_processes('memory', 3)
top_disk = self.get_top_processes('disk', 3)
# Update CPU processes
for i, (name, value, pid) in enumerate(top_cpu):
text = f"{name[:12]:<12} {value:>4.0f}%"
self.cpu_process_labels[i].config(text=text)
# Update Memory processes
for i, (name, value, pid) in enumerate(top_mem):
text = f"{name[:12]:<12} {value:>4.0f}%"
self.mem_process_labels[i].config(text=text)
# Update Disk processes
for i, (name, value, pid) in enumerate(top_disk):
text = f"{name[:12]:<12} {value/1024/1024:>3.0f}MB"
self.disk_process_labels[i].config(text=text)
except Exception as e:
print(f"Error updating process list: {e}")
def create_process_list(self, parent, title):
"""Create a frame with process list for a specific resource"""
frame = tk.Frame(parent, bg=self.card_color, padx=5, pady=5)
# Title
title_label = tk.Label(frame, text=title, bg=self.card_color, fg=self.accent_color,
font=('Segoe UI', 7, 'bold'))
title_label.pack(anchor='w', pady=(0, 1))
# Process list
process_frame = tk.Frame(frame, bg=self.card_color)
process_frame.pack(fill='x', pady=1)
# Create labels for top 3 processes
labels = []
for i in range(3):
label = tk.Label(process_frame, text="-"*20, bg=self.card_color, fg=self.fg_color,
font=('Consolas', 7), anchor='w')
label.pack(fill='x')
labels.append(label)
return frame, labels
def setup_ui(self):
"""Setup the user interface"""
# Main container
header_frame = tk.Frame(self.root, bg=self.bg_color, pady=10)
header_frame.pack(fill=tk.X, padx=10)
title_label = tk.Label(
header_frame,
text="System Monitor",
font=("Segoe UI", 14, "bold"),
bg=self.bg_color,
fg=self.accent_color
)
title_label.pack()
# Status indicator
self.status_label = tk.Label(
header_frame,
text="● Running",
font=("Segoe UI", 9),
bg=self.bg_color,
fg="#2ecc71"
)
self.status_label.pack()
# CPU Section
self.create_metric_section("CPU Usage", "cpu")
# HDD Section
self.create_metric_section("HDD Activity", "hdd")
# Network Section with process list directly below
network_frame = tk.Frame(self.root, bg=self.bg_color)
network_frame.pack(fill=tk.X, padx=5, pady=(0, 2))
self.create_metric_section("Network Usage", "network", parent=network_frame)
# Process monitoring section (directly under network section)
process_frame = tk.Frame(self.root, bg=self.bg_color, pady=0, padx=3)
process_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=3, pady=0)
# Create three columns for CPU, Memory, and Disk
cpu_frame, self.cpu_process_labels = self.create_process_list(process_frame, "TOP CPU PROCESSES")
cpu_frame.pack(side=tk.LEFT, fill='both', expand=True, padx=2)
mem_frame, self.mem_process_labels = self.create_process_list(process_frame, "TOP MEMORY PROCESSES")
mem_frame.pack(side=tk.LEFT, fill='both', expand=True, padx=2)
disk_frame, self.disk_process_labels = self.create_process_list(process_frame, "TOP DISK PROCESSES")
disk_frame.pack(side=tk.LEFT, fill='both', expand=True, padx=2)
# Light separator line above process list
sep = tk.Frame(process_frame, height=1, bg='#333333')
sep.pack(fill=tk.X, pady=(3, 2))
# Footer with version info (very compact, integrated with process frame)
footer_frame = tk.Frame(process_frame, bg=self.bg_color, height=1)
footer_frame.pack(side=tk.BOTTOM, fill=tk.X, pady=(2, 0))
footer_label = tk.Label(footer_frame, text="v1.0 | Right-click menu | Esc to exit",
font=('Segoe UI', 5), fg='#555555', bg=self.card_color)
footer_label.pack(pady=0)
def create_metric_section(self, title, metric_type, parent=None):
"""Create a section for a specific metric"""
# Use provided parent or default to root
parent = parent or self.root
# Main container with thinner frame and draggable header
section_frame = tk.Frame(parent, bg=self.bg_color, relief=tk.FLAT, bd=0)
section_frame.pack(fill=tk.X, padx=5, pady=3, ipady=0)
# Add a small handle for dragging at the top of the window
if not hasattr(self, '_drag_handle'):
self._drag_handle = tk.Frame(section_frame, bg=self.bg_color, height=20, cursor='fleur')
self._drag_handle.pack(fill=tk.X, pady=(0, 3))
self._drag_handle.bind('<Button-1>', self._on_drag_start)
self._drag_handle.bind('<B1-Motion>', self._on_drag_motion)
# Header with title and value - more compact
header_frame = tk.Frame(section_frame, bg=self.card_color, pady=2)
header_frame.pack(fill=tk.X, padx=5)
title_label = tk.Label(
header_frame,
text=title,
font=("Segoe UI", 10, "bold"),
bg=self.card_color,
fg=self.fg_color
)
title_label.pack(side=tk.LEFT)
value_label = tk.Label(
header_frame,
text="0%",
font=("Segoe UI", 12, "bold"),
bg=self.card_color,
fg=self.accent_color
)
value_label.pack(side=tk.RIGHT)
# Store reference to value label
setattr(self, f"{metric_type}_value_label", value_label)
# Graph frame - 50% smaller
graph_frame = tk.Frame(section_frame, bg=self.bg_color, height=40) # Reduced from 60px
graph_frame.pack(fill=tk.X, padx=2, pady=1) # Reduced padding
graph_frame.pack_propagate(False)
# Create matplotlib figure (smaller)
fig = Figure(figsize=(1.8, 0.6), dpi=80, facecolor=self.bg_color) # Reduced height
ax = fig.add_subplot(111)
ax.set_facecolor('#1a1a1a')
# Style the graph
ax.set_xlim(0, 59)
ax.set_ylim(0, 100)
ax.set_xticks([])
ax.set_yticks([])
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
# Color scheme for different metrics
colors = {
'cpu': '#0078d4',
'hdd': '#2ecc71',
'network': '#e74c3c'
}
line, = ax.plot([], [], color=colors[metric_type], linewidth=2)
ax.fill_between([], [], alpha=0.3, color=colors[metric_type])
# Store references
setattr(self, f"{metric_type}_fig", fig)
setattr(self, f"{metric_type}_ax", ax)
setattr(self, f"{metric_type}_line", line)
# Create canvas
canvas = FigureCanvasTkAgg(fig, graph_frame)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
# Details label - smaller and more compact
details_label = tk.Label(
section_frame,
text="Initializing...",
font=("Segoe UI", 6), # Smaller font
bg=self.bg_color, # Match window background
fg="#777777" # Lighter gray
)
details_label.pack(anchor=tk.W, padx=3, pady=(0, 1)) # Tighter padding
setattr(self, f"{metric_type}_details_label", details_label)
def get_cpu_usage(self):
# Match Task Manager's CPU usage calculation
return psutil.cpu_percent(interval=1, percpu=False)
def get_hdd_usage(self):
"""Get disk active time percentage similar to Task Manager's 'Active Time'"""
try:
# Get disk I/O statistics with per-disk details
disk_io = psutil.disk_io_counters(perdisk=True)
if not disk_io:
return 0.0
current_time = time.time()
total_io_ops = 0
total_bytes = 0
active_disks = 0
for disk_name, disk in disk_io.items():
# Skip non-physical disks, CD-ROMs, and RAM disks
if any(x in disk_name.lower() for x in ['cdrom', 'ram', 'loop', 'sr']):
continue
# Skip disks with no activity
if disk.read_count == 0 and disk.write_count == 0:
continue
# Calculate total I/O operations and bytes
total_io_ops += disk.read_count + disk.write_count
total_bytes += disk.read_bytes + disk.write_bytes
active_disks += 1
if active_disks == 0:
return 0.0
# Calculate I/O operations per second
if hasattr(self, '_last_disk_io') and hasattr(self, '_last_disk_time'):
time_delta = current_time - self._last_disk_time
if time_delta > 0:
# Calculate change in I/O operations
ops_delta = total_io_ops - getattr(self, '_last_disk_io', 0)
bytes_delta = total_bytes - getattr(self, '_last_disk_bytes', 0)
# Calculate operations per second and MB/s
ops_per_sec = ops_delta / time_delta
mb_per_sec = (bytes_delta / (1024 * 1024)) / time_delta
# Scale to 0-100% based on disk activity
# This is a heuristic that works well for most systems
activity = min(100, (ops_per_sec * 0.1) + (mb_per_sec * 5))
# Store current values for next iteration
self._last_disk_io = total_io_ops
self._last_disk_bytes = total_bytes
self._last_disk_time = current_time
return min(100, max(0, activity))
# Initialize for first run
self._last_disk_io = total_io_ops
self._last_disk_bytes = total_bytes
self._last_disk_time = current_time
return 0.0
except Exception as e:
print(f"HDD monitoring error: {e}")
return 0.0
def get_network_usage(self):
"""Get network utilization percentage"""
try:
net_io = psutil.net_io_counters(pernic=True)
if not net_io:
return 0.0
# Find the active network interface
active_interface = None
for interface, stats in net_io.items():
if interface == 'lo' or interface.startswith('Loopback'):
continue
active_interface = interface
break
if not active_interface:
return 0.0
current_time = time.time()
time_delta = current_time - getattr(self, '_last_network_time', current_time)
self._last_network_time = current_time
bytes_sent = net_io[active_interface].bytes_sent
bytes_recv = net_io[active_interface].bytes_recv
if hasattr(self, '_last_sent_bytes'):
self.last_send_rate = (bytes_sent - self._last_sent_bytes) / 1024 / time_delta
self.last_recv_rate = (bytes_recv - self._last_recv_bytes) / 1024 / time_delta
else:
self.last_send_rate = 0
self.last_recv_rate = 0
self._last_sent_bytes = bytes_sent
self._last_recv_bytes = bytes_recv
# Calculate utilization
total_bps = (self.last_send_rate + self.last_recv_rate) * 1024 * 8
interface_speed_bps = self.network_speed_mbps * 1_000_000
raw_utilization = (total_bps / interface_speed_bps) * 100 if interface_speed_bps > 0 else 0
# Apply smoothing
if hasattr(self, '_last_net_util'):
utilization = (raw_utilization * 0.3) + (self._last_net_util * 0.7)
else:
utilization = raw_utilization
self._last_net_util = utilization
return min(utilization, 100)
except Exception as e:
return getattr(self, '_last_net_util', 0.0)
def update_graph(self, metric_type, value):
try:
# Schedule the graph update on the main thread
if not hasattr(self, '_graph_update_pending'):
self._graph_update_pending = {}
# Only schedule an update if one isn't already pending for this metric
if not self._graph_update_pending.get(metric_type, False):
self._graph_update_pending[metric_type] = True
self.root.after(0, self._process_graph_updates, metric_type, value)
except Exception as e:
print(f"Error scheduling graph update for {metric_type}: {e}")
def _process_graph_updates(self, metric_type, value):
try:
# Mark that we're processing this update
self._graph_update_pending[metric_type] = False
# Get the UI elements
data = getattr(self, f"{metric_type}_data")
line = getattr(self, f"{metric_type}_line")
ax = getattr(self, f"{metric_type}_ax")
fig = getattr(self, f"{metric_type}_fig")
# Ensure value is a number
try:
value = float(value)
except (ValueError, TypeError):
value = 0
# Update the data
data.append(value)
x_data = list(range(len(data)))
y_data = list(data)
# Update the plot
with threading.Lock():
# Update the line data
line.set_data(x_data, y_data)
# Clear existing fill
for coll in ax.collections[:]:
coll.remove()
# Redraw the fill
ax.fill_between(x_data, y_data, alpha=0.3, color=line.get_color())
# Set Y-axis range based on metric type
if metric_type == 'network':
# For network, use dynamic scaling up to 2x the max value (with min 10% range)
max_val = max(data) if data else 10
y_max = max(10, min(100, max_val * 2)) # Cap at 100% but allow up to 2x current max
ax.set_ylim(0, y_max)
else:
# For CPU and HDD, keep 0-100% range
ax.set_ylim(0, 100)
# Redraw the canvas
fig.canvas.draw_idle() # Use draw_idle instead of draw for better performance
except Exception as e:
# Reset the pending flag if there was an error
if hasattr(self, '_graph_update_pending'):
self._graph_update_pending[metric_type] = False
if hasattr(self, '_ui_update_pending'):
self._ui_update_pending = False
def _update_ui(self, cpu_usage, hdd_usage, network_usage):
try:
with threading.Lock():
# Update value labels
self.cpu_value_label.config(text=f"{cpu_usage:.1f}%")
self.hdd_value_label.config(text=f"{hdd_usage:.1f}%")
self.network_value_label.config(text=f"{network_usage:.1f}%")
# Update CPU details
if hasattr(self, 'cpu_data') and self.cpu_data:
try:
cpu_avg = sum(self.cpu_data) / len(self.cpu_data)
cpu_peak = max(self.cpu_data)
self.cpu_details_label.config(text=f"Avg: {cpu_avg:.1f}% | Peak: {cpu_peak:.1f}%")
except (ValueError, ZeroDivisionError):
pass
# Get disk I/O for details
try:
disk_io = psutil.disk_io_counters()
if disk_io:
read_mb = disk_io.read_bytes / (1024 * 1024)
write_mb = disk_io.write_bytes / (1024 * 1024)
self.hdd_details_label.config(text=f"R/W: {read_mb:.1f}MB/{write_mb:.1f}MB")
except Exception as e:
print(f"Error getting disk I/O: {e}")
# Network details
try:
if hasattr(self, 'last_send_rate') and hasattr(self, 'last_recv_rate'):
self.network_details_label.config(
text=f"↓{self.last_recv_rate:.1f} ↑{self.last_send_rate:.1f} KB/s"
)
except Exception as e:
print(f"Error updating network details: {e}")
# Force update the display
self.root.update_idletasks()
except Exception as e:
print(f"Error in UI update: {e}")
finally:
# Always reset the update flag, even if there was an error
self._ui_update_pending = False
def update_metrics(self):
"""Update all metrics"""
try:
# Get current values
cpu_percent = psutil.cpu_percent(interval=0.1)
hdd_usage = self.get_hdd_usage()
net_usage = self.get_network_usage()
# Update graphs
self.update_graph('cpu', cpu_percent)
self.update_graph('hdd', hdd_usage)
self.update_graph('network', net_usage)
# Update labels
self.cpu_value_label.config(text=f"{cpu_percent:.1f}%")
self.hdd_value_label.config(text=f"{hdd_usage:.1f}%")
self.network_value_label.config(text=f"{net_usage:.1f}%")
# Update process list (less frequently to reduce CPU usage)
if not hasattr(self, '_last_process_update') or (time.time() - self._last_process_update) > 2:
self.update_top_processes()
self._last_process_update = time.time()
except Exception as e:
print(f"Error updating metrics: {e}")
# Schedule next update
self.update_job = self.root.after(1000, self.update_metrics)
def monitor_thread(self):
while getattr(self, '_running', True):
try:
# Update metrics directly instead of using after()
# This prevents queue buildup if the main thread is busy
self.update_metrics()
time.sleep(1) # Update every second
except Exception as e:
print(f"Monitor error: {e}")
time.sleep(1) # Prevent tight loop on error
def start_monitoring(self):
# Set running flag
self._running = True
# Start monitoring in a separate thread
self.monitor_thread = threading.Thread(target=self.monitor_thread, daemon=True)
self.monitor_thread.start()
def stop_monitoring(self):
# Signal the monitoring thread to stop
self._running = False
if hasattr(self, 'monitor_thread') and self.monitor_thread.is_alive():
self.monitor_thread.join(timeout=2.0)
def main():
root = tk.Tk()
app = SystemMonitor(root)
# Handle window close
def on_closing():
# Stop monitoring thread
if hasattr(app, 'stop_monitoring'):
app.stop_monitoring()
# Close the window
root.quit()
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
try:
root.mainloop()
except KeyboardInterrupt:
on_closing()
except Exception as e:
print(f"Unexpected error: {e}")
on_closing()
if __name__ == "__main__":
main()