Search code examples
pythonpsutil

Python psutil module, why does it end up with an exception when i call .exe() method before an if statement


I'm working on a project that requires me using psutil, I was trying to compare some values to that of a .txt file's but for some reason whenever I called the psutil.Procces.exe() method outside an if statement it'd end up with an Access Denied exception, let me show you what I mean:

import psutil
import time

ini = 'start'

def getTaskList():
    list_of_ran_proccesses = []
    for procs in psutil.process_iter():
        list_of_ran_proccesses.append(procs)
    return list_of_ran_proccesses

def CompareRunningFiles():
    if ini == "start":
        list_of_old_procs = getTaskList()
        while list_of_old_procs == getTaskList():
            time.sleep(0.01)
        for new_procs in psutil.process_iter():
            if not new_procs in list_of_old_procs:
                print(new_procs.exe())  

CompareRunningFiles()    

This example works completely fine but if i do this

import psutil
import time

ini = 'start'

def getTaskList():
    list_of_ran_proccesses = []
    for procs in psutil.process_iter():
        list_of_ran_proccesses.append(procs)
    return list_of_ran_proccesses

def CompareRunningFiles():
    if ini == "start":
        list_of_old_procs = getTaskList()
        while list_of_old_procs == getTaskList():
            time.sleep(0.01)
        for new_procs in psutil.process_iter():
            print(new_procs.exe())

CompareRunningFiles()

This for some reason ends up with an Access Denied exception. Thank you for all your answers :)

Edit: I'm not sure but, can this be because the module is trying to access some protected directories?

Because after the if statement it would only try to get the directory of whatever process was launched but without the if statement it'd try and access all sorts of running processes.

So when it comes across a system process, it'd try and get it's directory too, which if the process runs inside a protected directory it would raise an Access Denied exception.


Solution

  • Basically, the if statement there prevents the program from trying to get the directory of some system processes(They are always on), some directories in Windows are protected and cannot be accessed directly which, without the if statement the module is trying to get the directories of all running processes and this causes an exception when it tries to do that for a process that's running from a protected directory (example: System Idle Process), using (as Omer said) a "try:... except psutil.AccessDenied: pass" will skip those processes and prevent this issue. Thank you Omer for the explanation and tripleee for the same :D