I have a simple piece of code taken mostly from this answer, with some adjustments:
import psutil try: if "firefox.exe" in (p.name() for p in psutil.process_iter()): print('Firefox is running') else: print('Firefox is not running') except Exception as e: print(e)
If Firefox is running when I run this code, it prints the expected
Firefox is running. But if firefox isn’t running, I get
psutil.AccessDenied (pid=9092) instead of the expected
Firefox is not running.
I also noticed that if
firefox.exe is misspelled, I get the
AccessDenied error again. I could just
print('Firefox is not running') inside the except block, but that doesn’t seem very smart.
Does anyone know why this is happening?
process_iter() allows you to specify the attributes that should be returned. So tell it to just return the names, and compare them.
if any(p.info['name'] == "firefox.exe" for p in psutil.process_iter(['name'])):
Got this from the documentation: