1.2 MiB
1.2 MiB
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 = psutil.cpu_percent(interval=1) | 7 cpu = psutil.cpu_percent(interval=1)
8 - mem = psutil.virtual_memory() |
9 - timestamp = time.strftime('%Y-%m-%d %H:%M:%S') |
10 - log_entry = f"{timestamp} CPU: {cpu}% Memory: {mem.percent}%\n" |
| 8 + memory = psutil.virtual_memory().percent
| 9 + log_entry = f"CPU: {cpu}%, Memory: {memory}%\n"
11 log_file.write(log_entry) | 10 log_file.write(log_entry)
12 log_file.flush() | 11 log_file.flush()
13 - time.sleep(4) # Already waited 1 sec in cpu_percent, so sleep 4 more to total 5 |
| 12 + time.sleep(4)
14 except KeyboardInterrupt: | 13 except KeyboardInterrupt:
15 - 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 handles keyboard interrupts gracefully.
----------------------------------------
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 = psutil.cpu_percent(interval=1) | 7 cpu = psutil.cpu_percent(interval=1)
8 - mem = psutil.virtual_memory() |
9 - timestamp = time.strftime('%Y-%m-%d %H:%M:%S') |
10 - log_entry = f"{timestamp} CPU: {cpu}% Memory: {mem.percent}%\n" |
| 8 + memory = psutil.virtual_memory().percent
| 9 + log_entry = f"CPU: {cpu}%, Memory: {memory}%\n"
11 log_file.write(log_entry) | 10 log_file.write(log_entry)
12 log_file.flush() | 11 log_file.flush()
13 - time.sleep(4) # Already waited 1 sec in cpu_percent, so sleep 4 more to total 5 |
| 12 + time.sleep(4)
14 except KeyboardInterrupt: | 13 except KeyboardInterrupt:
15 - 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 handles keyboard interrupts gracefully.