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...
|
||
|
||
[Agent] Iteration 1/300
|
||
[Agent] has_tool_calls=true
|
||
[Agent] Executing 1 tool(s)
|
||
-> Writing file: system_monitor.py
|
||
[2m[parallel] launching write_file[0m
|
||
|
||
[36m [2m CHANGES: system_monitor.py [0m
|
||
LINE OLD | LINE NEW
|
||
--------------------------------------------------------------------------------------------------------------------------------------------
|
||
1 import psutil | 1 import psutil
|
||
2 import time | 2 import time
|
||
3 [31m-[0m [31mimport logging [0m |
|
||
4 | 3
|
||
5 [31m-[0m [31m# Configure logging [0m |
|
||
6 [31m-[0m [31mlogging.basicConfig(filename='usage.log', level=logging.INFO, format='%(asctime)s - %(message)s') [0m |
|
||
| 4 [32m+[0m [32mLOG_FILE = 'usage.log' [0m
|
||
| 5 [32m+[0m [32mINTERVAL = 5 # seconds [0m
|
||
7 | 6
|
||
8 try: | 7 try:
|
||
9 [31m-[0m [31m while True: [0m |
|
||
10 [31m-[0m [31m cpu_usage = psutil.cpu_percent(interval=1) [0m |
|
||
11 [31m-[0m [31m mem = psutil.virtual_memory() [0m |
|
||
12 [31m-[0m [31m mem_usage = mem.percent [0m |
|
||
13 [31m-[0m [31m log_message = f"CPU Usage: {cpu_usage}%, Memory Usage: {mem_usage}%" [0m |
|
||
14 [31m-[0m [31m print(log_message) [0m |
|
||
15 [31m-[0m [31m logging.info(log_message) [0m |
|
||
16 [31m-[0m [31m time.sleep(4) [0m |
|
||
17 [31m-[0m [31mexcept KeyboardInterrupt: [0m |
|
||
18 [31m-[0m [31m print("Monitoring stopped by user.") [0m |
|
||
19 [31m-[0m [31m pass [0m |
|
||
| 8 [32m+[0m [32m with open(LOG_FILE, 'a') as log: [0m
|
||
| 9 [32m+[0m [32m while True: [0m
|
||
| 10 [32m+[0m [32m cpu_percent = psutil.cpu_percent(interval=1) [0m
|
||
| 11 [32m+[0m [32m mem = psutil.virtual_memory() [0m
|
||
| 12 [32m+[0m [32m log_entry = f"CPU: {cpu_percent}%, Memory: {mem.percent}%\n" [0m
|
||
| 13 [32m+[0m [32m log.write(log_entry) [0m
|
||
| 14 [32m+[0m [32m log.flush() [0m
|
||
| 15 [32m+[0m [32m print(log_entry.strip()) [0m
|
||
| 16 [32m+[0m [32m time.sleep(INTERVAL - 1) [0m
|
||
| 17 [32m+[0m [32mexcept KeyboardInterrupt: [0m
|
||
| 18 [32m+[0m [32m print('Monitoring stopped by user.') [0m
|
||
|
||
[Agent] Iteration 2/300
|
||
The script [33msystem_monitor.py[0m has been created. It logs CPU and memory usage to [33musage.log[0m every 5 seconds and handles keyboard interrupts gracefully. Would you like to review or run this script?
|
||
[Agent] has_tool_calls=false
|
||
[Agent] Response indicates incomplete work, auto-continuing
|
||
[Agent] Iteration 3/300
|
||
The script [33msystem_monitor.py[0m has been successfully created. You can now run it to start logging CPU and memory usage every 5 seconds. Would you like me to execute the script for you or provide instructions on how to run it?
|
||
[Agent] has_tool_calls=false
|
||
[Agent] Completed in 3 iteration(s)
|