35 lines
1.5 MiB
Plaintext
Raw Normal View History

2026-01-29 06:54:10 +01:00
TASK: Write a Python script 'system_monitor.py' that logs CPU and memory usage to 'usage.log' every 5 seconds. Ensure it handles keyboard interrupts.
----------------------------------------
Loading...
-> Writing file: system_monitor.py
  CHANGES: system_monitor.py 
LINE OLD
--------------------------------------------------------------------------------------------------------------------------------------------
1 import psutil
2 import time
2026-01-29 07:42:06 +01:00
3
4 - LOG_FILE = 'usage.log'
5 - INTERVAL = 5 # seconds
6 - 
7 try:
8 -  with open(LOG_FILE, 'a') as log:
9 while True:
10 cpu_percent = psutil.cpu_percent(interval=1)
11 mem = psutil.virtual_memory()
12 log_entry = f"CPU: {cpu_percent}%, Memory: {mem.percent}%\n"
13 -  log.write(log_entry)
14 -  log.flush()
15 -  print(log_entry.strip())
16 -  time.sleep(INTERVAL - 1)
17 except KeyboardInterrupt:
18 -  print('Monitoring stopped by user.')
2026-01-29 06:54:10 +01:00
2026-01-29 07:42:06 +01:00
The script 'system_monitor.py' has been created. It logs CPU and memory usage to 'usage.log' every 5 seconds and gracefully handles keyboard interrupts. If you need to run it or modify it further, let me know!