3

我有一个 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进程?

4

1 回答 1

0

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

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

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

在一个无限循环中,我连续调用这个函数,中间有一个短暂的休息。如果任何进程特定的元组在运行中是相同的,则相应进程的内存消耗不会改变——这个进程现在可以被 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
于 2018-03-08T03:26:58.623 回答