You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法在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 your s=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 replaces os.system() and captures the actual text output of your command. The text=True parameter saves you from having to decode raw bytes into a string manually.
  • Append mode ('a'): Using with 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-except block catches issues like command failures (e.g., top not being available, grep finding 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 True loop 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:

  1. Run the entire Python script with sudo: sudo python3 your_script.py
  2. Or configure passwordless sudo for the top command (edit /etc/sudoers carefully with visudo to avoid locking yourself out).

内容的提问来源于stack exchange,提问作者Shubham R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:34:05