Search code examples
pythonkill-processpsutil

How To Kill Process With Minimum Processor Consumption


I was looking for a python script to kill particular running process(s). I got a script to get list of all currently running processes. So I did some modifications and it works as follows:

A list named blackList stores all the unwanted processes which needs to be killed. The script iterates through fetched process names and compares with the blackList's content. If it matches, then that process is terminated.

Code:

import psutil

blackList = ["SkypeHost.exe", "Music.UI.exe", "SearchUI.exe", "Video.UI.exe", "backgroundTaskHost.exe"]

while True:
  for proc in psutil.process_iter():
    try:
        pinfo = proc.as_dict(attrs=['pid', 'name', 'username'])
    except psutil.NoSuchProcess:
        pass
    else:
        for i in blackList:
            if pinfo["name"] == i:
                proc.kill()

The script works fine but its consuming much of my processor.

Without running the script

Without running the script

While Script is running

While Script is running

Is there any way to minimize this consumption? Why is it consuming so much of processor?

My processor: Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz


Solution

  • import time
    

    and throw a time.sleep(some small time frame) in your loop.

    Doing while True with no break is going to thrash your cpu.