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

如何使用psutil终止超过特定时长的闲置进程?

如何用psutil终止长时间闲置的特定进程

Hey there! Let's tweak your code to target only those idle Application.exe processes that have been running longer than your threshold. Here's a practical approach using psutil, with explanations along the way:

Step-by-Step Solution

First, we need to define what "idle" means for your use case. For most scenarios, we can combine two checks:

  • The process has been running longer than your set threshold
  • The process is using minimal CPU (indicating it's not actively doing work)

Here's the revised code:

import psutil
import time

# Define your idle threshold in seconds (e.g., 3600s = 1 hour)
IDLE_THRESHOLD = 3600

# Iterate over processes, fetching only the info we need for efficiency
for proc in psutil.process_iter(['pid', 'name', 'create_time', 'cpu_percent']):
    try:
        # Match your target process name
        if 'Application.exe' in proc.info['name']:
            # Calculate how long the process has been running
            run_duration = time.time() - proc.info['create_time']
            
            # Check if it's over the threshold AND idle (low CPU usage)
            if run_duration > IDLE_THRESHOLD and proc.info['cpu_percent'] < 1:
                print(f"Terminating idle process: {proc.info['name']} (PID: {proc.info['pid']}) | Ran for {round(run_duration/3600, 1)} hours")
                proc.kill()
    except (psutil.NoSuchProcess, psutil.AccessDenied):
        # Ignore cases where the process disappears mid-check or we lack permissions
        continue

Key Details Explained

  • Efficient Process Info: By passing a list of fields to psutil.process_iter(), we avoid unnecessary system calls and speed up the iteration.
  • Run Duration Calculation: proc.info['create_time'] gives the Unix timestamp when the process started. Subtract this from the current time (time.time()) to get total runtime in seconds.
  • Idle Check: Using cpu_percent < 1 ensures we only target processes that aren't actively using CPU. Adjust this value if your app might use a tiny bit of CPU while idle.
  • Error Handling: Processes can vanish or restrict access during iteration, so we catch common exceptions to keep the script running smoothly.

Notes for Your Use Case

  • If you strictly need to check for user inactivity (e.g., a GUI app that hasn't been clicked in hours), psutil doesn't have a built-in way to get this. On Windows, you'd need to pair it with something like pywin32 to access system-level input tracking. But for most server/background processes, the CPU+runtime check works perfectly.
  • Always test first! Comment out the proc.kill() line and run the script to verify which processes it will target before letting it terminate anything.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:49:36