无法在Python中执行top终端命令,求助定时保存内存信息方案
Fixing Your Memory Monitoring Script
Hey there, let's work through this step by step to get your memory logging script up and running properly.
First, let's break down why your current approach isn't working:
os.system()only returns the exit status code of the command (0 for success, non-zero for errors), not the actual output you see in the terminal. That's why yours=str(top)is just a number instead of the memory stats you need.- You're opening the file in write mode (
'w'), which overwrites the file every time—you want append mode ('a') to keep all historical records. - The order of operations in your
repeat()function is off; you should run the command and write to the file before setting the next timer to maintain consistent 10-second intervals.
Here's the corrected, working script
import time import threading import subprocess def log_memory_stats(): # Get human-readable timestamp for each entry timestamp = time.ctime() try: # Execute the top command and capture its output directly # shell=True lets us use the pipe | operator in the command output = subprocess.check_output( "top -d 1.0 -n 1 | grep Mem", shell=True, text=True # Returns string output instead of raw bytes ) # Format the entry for readability log_entry = f"[{timestamp}]\n{output}\n" # Open file in append mode to preserve previous logs with open('ss.txt', 'a') as f: f.write(log_entry) print(f"Logged memory stats at {timestamp}") except subprocess.CalledProcessError as e: print(f"Error running command: {e}") # Schedule the next run exactly 10 seconds later threading.Timer(10, log_memory_stats).start() # Start the monitoring loop if __name__ == "__main__": print("Starting memory monitoring. Press Ctrl+C to stop.") log_memory_stats() # Keep the main thread alive so the timer can run try: while True: time.sleep(1) except KeyboardInterrupt: print("\nMonitoring stopped successfully.")
Key improvements explained:
subprocess.check_output(): This replacesos.system()and captures the actual text output of your command. Thetext=Trueparameter saves you from having to decode raw bytes into a string manually.- Append mode (
'a'): Usingwith open('ss.txt', 'a')ensures each new log entry is added to the end of the file, instead of wiping previous data. - Error handling: The
try-exceptblock catches issues like command failures (e.g.,topnot being available,grepfinding no matches) and prints a helpful message instead of crashing the script. - Consistent scheduling: The timer is set after successfully logging the stats, so your 10-second interval stays reliable.
- Main thread keep-alive: The
while Trueloop prevents the script from exiting immediately after setting the first timer.
Quick note about sudo:
Most systems don't require sudo to run top, but if you do need it:
- Run the entire Python script with sudo:
sudo python3 your_script.py - Or configure passwordless sudo for the
topcommand (edit/etc/sudoerscarefully withvisudoto avoid locking yourself out).
内容的提问来源于stack exchange,提问作者Shubham R
相关产品推荐
相关产品推荐

