如何使用 python 终止资源消耗不变的 windows 进程?

How to kill windows processes whose resource consumption doesn't change using python?

我有一个 python 脚本来测试我的 windows 机器上是否有任何 firefox 进程 运行 然后杀死它们:

import os, subprocess
running_processes = subprocess.check_output('tasklist', shell = True)
if "firefox.exe" in running_processes:
    os.system("TASKKILL /F /IM firefox.exe")

我只想杀死内存消耗和 CPU 使用率随时间保持不变(即在特定时间间隔内不改变)的 firefox 进程。

如何在 python 中终止具有常量内存和 CPU 用法的 windows 进程?

我目前杀死陈旧 windows 进程的方法涉及一个函数,该函数 returns 每个 运行 进程的(进程 PID / 进程内存消耗)元组。

如果元组在两次连续的函数调用之间没有变化,我会通过 PID 终止进程。这种方法有一个局限性:to-be-monitored 过程需要提前知道(命名)。

import os, subprocess, csv, psutil, time
def get_task_memory(process_name):
    running_processes = csv.DictReader(              # Get list of running processes
                             subprocess.check_output(
                             \"tasklist /fo csv\").splitlines()) 
    PID_list = []
    memory_A = []
    for task in running_processes:                   # Loop through running processes
        if process_name in task.values():
            PID = int(task.values()[2])              # Get process PID
            consumption = task.values()[1]           # Get memory usage of process with PID
            PID_list.append(PID)                     # Create list of PIDs
            memory_A.append(consumption)             # Create list of memory usage
    process_snapshot = zip(PID_list, memory_A)       # Create list of PID:memory usage tuples
    return process_snapshot                          # return tuple for every running process

在无限循环中,我连续调用此函数,中间有短暂的中断。如果任何 process-specific 元组在运行过程中是相同的,则相应进程的内存消耗没有改变——这个进程现在可以被 PID 杀死。

while True:  
    process_name = "phantomjs.exe"                     # PName of process to be monitored
    process_snapshot_A = get_task_memory(process_name) # function call 1
    time.sleep(n)                                      # Wait
    process_snapshot_B = get_task_memory(process_name) # function call 2
    stale_processes = [tuple for tuple in process_snapshot_A if tuple in process_snapshot_B]
    if len(stale_processes) > 0:                       # Stale processes 
        print "stale process found - terminating"
        for PID, memory in stale_processes:            
            stale_process = psutil.Process(PID)        # Get PID
            stale_process.kill()                       # Kill PID
    else:
        pass