Question

This works perfectly:

def find_processes():
    name = "ProcessName.exe"
    pid_list = psutil.get_pid_list()
    for pid in pid_list:
        try:
            if str(psutil.Process(pid).name()) == name:
                return True
        except:
            pass
    return False

This doesn't:

def find_processes():
    name = "ProcessName.exe"
    pid_list = psutil.get_pid_list()
    for pid in pid_list:
        if str(psutil.Process(pid).name()) == name:
            return True
    return False

It raises an error: AccessDenied: (pid=560) I'm on a Windows environment and need to access all the processes' names. I already have a working code (the former), so my question is more out of curiosity.

What do the try/except statements do in the first example, and why is it not working if I remove them in the second?

Was it helpful?

Solution

Not all of the information from each process will be available to you unless you are the root user/administrator. See this question: python psutil on windows gives access denied.

You would be better off changing your first example to specifically catch these cases, with:

try:    
    if str(psutil.Process(pid).name()) == name:      
        return True    
except AccessDenied:    
    print "Unable to access PID:",pid
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top