我有一个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进程的方法涉及一个函数,该功能可在每个运行过程中返回(过程PID/Process Memory消耗(的元组。
如果元组在两个连续的函数调用之间没有更改,则我通过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