简体   繁体   中英

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".

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")

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM