Home > Back-end >  Process is not found if opened until a lot of searches
Process is not found if opened until a lot of searches

Time:06-20

import psutil

name = "notepad.exe"

for proc in psutil.process_iter():
    if proc.name().lower() == name.lower():
        print("found")
    elif proc.name().lower() != name.lower():
        print("not found")

output:

not found
not found
not found
found
not found
not found

"notepad.exe" was open from the start and until the end of the script.

CodePudding user response:

It seems to me you could use any() rather than using a for loop:

if any(proc.name().lower() == name.lower() for proc in psutil.process_iter()):
    print("found")
else
    print("not found")

CodePudding user response:

psutil.process_iter() gives you an generator of all running processes.

Hi whytfnotworking. Your code behaves as it should. Remember than, as the psutil.process_iter documentation says, it will iterates over all the running processes. In a typical machine you can have hundreds of them (I have at least 238 running right now). So, if you want to just get the one your'e interested in, you could simply remove the last two lines:

import psutil

name = "notepad.exe"

for proc in psutil.process_iter():
    if proc.name().lower() == name.lower():
        print("found")
        break #This is for stop the iteration once found

Edit:

If you want to see when it's not found, then you could make use of an powerful, yet non popular feature of python loops: the else (yes, else in loops... python is amazing).

import psutil

name = "notepad.exe"

for proc in psutil.process_iter():
    if proc.name().lower() == name.lower():
        print("found")
        break #This is for stop the iteration once found
else:
    print("not found") #It will get executed when the loop ends normally (not breaked)
  • Related