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 - LOG_FILE = 'usage.log'  |
5 - INTERVAL = 5 # seconds  |
6 -   |
7 try: | 4 try:
8 -  with open(LOG_FILE, 'a') as log:  |
| 5 +  with open('usage.log', 'a') as log_file: 
9 while True: | 6 while True:
10 cpu_percent = psutil.cpu_percent(interval=1) | 7 cpu_percent = psutil.cpu_percent(interval=1)
11 mem = psutil.virtual_memory() | 8 mem = psutil.virtual_memory()
12 log_entry = f"CPU: {cpu_percent}%, Memory: {mem.percent}%\n" | 9 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)  |
| 10 +  log_file.write(log_entry) 
| 11 +  log_file.flush() 
| 12 +  time.sleep(4) 
17 except KeyboardInterrupt: | 13 except KeyboardInterrupt:
18 -  print('Monitoring stopped by user.')  |
| 14 +  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. If you need to run it or modify it further, let me know!