pythonmemory-managementcpu-usagetaskkillwindows-process

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


I have a python script that tests if any firefox processes are running on my windows machine and then kills them:

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

I would like to only kill firefox processes whose memory consumption and CPU usage are constant over time (i.e. do not change within a certain interval).

How to kill windows processes with constant memory and CPU usage in python?


Solution

  • My current approach to kill stale windows processes involves a function that returns a tuple of (process PID / process memory consumption) for every running process.

    If the tuple doesn't change between two consecutive function calls, I kill the process by PID. This approach has one limitation: The to-be-monitored process needs to be known (named) in advance.

    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
    

    In an endless loop, I call this function consecutively with a short break in between. In case any process-specific tuple is identical across runs, the memory consumption of the respective process did not change - this process can now be killed by 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