KAKAK
KAKAK

Reputation: 899

Find if process is running in Windows psutil

process_name = "CCC.exe"
for proc in psutil.process_iter():
    if proc.name == process_name:
        print ("have")
    else: 
        print ("Dont have")

I know for the fact that CCC.exe is running. I tried this code with both 2.7 and 3.4 python I have imported psutil as well. However the process is there but it is printing "Dont have".

Upvotes: 2

Views: 14764

Answers (3)

vuolter
vuolter

Reputation: 41

name is a method of proc:

process_name = "CCC.exe"
for proc in psutil.process_iter():
    if proc.name() == process_name:
        print ("have")
    else: 
        print ("Dont have")

Upvotes: 4

ρss
ρss

Reputation: 5315

Here is the modified version that worked for me on Windows 7 with python v2.7

You were doing it in a wrong way here if proc.name == process_name: in your code. Try to print proc.name and you'll notice why your code didn't work as you were expecting.

Code:

import psutil
process_name = "System" 
for proc in psutil.process_iter(): 
    process = psutil.Process(proc.pid)# Get the process info using PID
    pname = process.name()# Here is the process name
    #print pname
    if pname == process_name: 
        print ("have") 
    else: print ("Dont have")

Here are some examples about how to use psutil. I just read them and figured out this solution, may be there is a better solution. I hope it was helpful.

Upvotes: 0

KAKAK
KAKAK

Reputation: 899

I solved it by using WMI instead of psutil. https://pypi.python.org/pypi/WMI/

install it on windows.

import wmi c = wmi.WMI () for process in c.Win32_Process (): if "a" in process.Name: print (process.ProcessId, process.Name)

Upvotes: 0

Related Questions