import psutil import time LOG_FILE = 'usage.log' INTERVAL = 5 # seconds try: with open(LOG_FILE, 'a') as log: while True: cpu_percent = psutil.cpu_percent(interval=1) mem = psutil.virtual_memory() log_entry = f"CPU: {cpu_percent}%, Memory: {mem.percent}%\n" log.write(log_entry) log.flush() print(log_entry.strip()) time.sleep(INTERVAL - 1) except KeyboardInterrupt: print('Monitoring stopped by user.')