Reputation: 312
I'm using psutil in order to know when a process is running.
So far I have this code:
PROCESS_NAME = 'python.exe'
for p in psutil.process_iter():
if p.name == PROCESS_NAME:
print("It's alive!")
break
However, it doesn't seem to work.
I've looked around on google and here but every post suggests that the code above would be correct.
Unless I'm clearly misunderstanding how process_iter() works....
Upvotes: 0
Views: 1018
Reputation: 168626
This line is wrong:
if p.name == "PROCESS_NAME": # BAD
It looks for a process whose name is, literally, «PROCESS_NAME». Instead, you want to look for a process whose name is the same as the name referred to by the variable PROCESS_NAME, like so:
if p.name == PROCESS_NAME: # GOOD
The right-hand-side of the first line is a string literal. The right-hand-side of the second is the name of a variable.
Of course, if you are always going to look for the same name, you can put that name in a string literal:
if p.name == "python.exe": # ALSO GOOD
Between version 1.2.1 and version 2 of psutil
, they changed the api. In version 1, p.name
is the name of the process. In version 2, p.name
is a function which returns a string which is the name of the process.
So, try this:
if p.name() == PROCESS_NAME:
Upvotes: 1