我目前杀死陈旧 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