This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 | LINE NEW
--------------------------------------------------------------------------------------------------------------------------------------------
1 import psutil | 1 import psutil
2 import time | 2 import time
3 | 3
4 try: | 4 try:
5 with open('usage.log', 'a') as log_file: | 5 with open('usage.log', 'a') as log_file:
6 while True: | 6 while True:
7 -  cpu_percent = psutil.cpu_percent(interval=1)  |
| 7 +  cpu = psutil.cpu_percent(interval=1) 
8 mem = psutil.virtual_memory() | 8 mem = psutil.virtual_memory()
9 -  log_entry = f"CPU: {cpu_percent}%, Memory: {mem.percent}%\n"  |
| 9 +  timestamp = time.strftime('%Y-%m-%d %H:%M:%S') 
| 10 +  log_entry = f"{timestamp} CPU: {cpu}% Memory: {mem.percent}%\n" 
10 log_file.write(log_entry) | 11 log_file.write(log_entry)
11 log_file.flush() | 12 log_file.flush()
12 -  time.sleep(4)  |
| 13 +  time.sleep(4) # Already waited 1 sec in cpu_percent, so sleep 4 more to total 5 
13 except KeyboardInterrupt: | 14 except KeyboardInterrupt:
14 -  print("Monitoring stopped by user.")  |
| 15 +  print("Monitoring stopped by user.")"} 
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.