Reputation: 43
I have a function that should return the process ID of a given process using psutil, but for some reason it doesn't return anything.
Printing the required variable shows the correct value. I think I'm doing something wrong.
def pid_find(process_name):
pid = []
for proc in psutil.process_iter():
try:
if proc.name() == process_name:
pid.append(proc.pid)
except psutil.AccessDenied:
pass
try:
process = pid[0]
except IndexError:
raise Exception("Process %s not found" % process_name)
print process # prints the correct value
return process # does not return anything
Upvotes: 0
Views: 1946
Reputation: 1025
With some simplification, but with your code spirit :
import psutil
def pid_find(process_name):
for proc in psutil.process_iter():
try:
if (proc.name()) == process_name:
return proc.pid
except psutil.AccessDenied:
pass
raise Exception("Process %s not found" % process_name)
print pid_find("bash")
Upvotes: -1
Reputation: 43
I think I found the problem. The function is working fine, but I was not debugging correctly to check if the function works:
This is how I tried:
Function is located in file functions.py file
I was calling the function in the test.py file like this:
import functions
def debug
functions.pid_find("chrome.exe)
if __name__ == "__main__":
debug()
But if I put the function into a variable, I should be able to store the result and use it further:
import functions
def debug(proc):
pid = functions.pid_find(proc)
print pid #shows that pid has the correct value
Upvotes: 0
Reputation: 2326
can be done with wmi query without iterations:
from win32com.client import Dispatch
import wmi
server = Dispatch("WbemScripting.SWbemLocator")
c = server.ConnectServer("localhost", "root\\cimv2")
process_query = "Select * from Win32_Process Where Namse like '%{0}%'".format(cmd_argument)
process = c.ExecQuery(process_query)
for i in process[0].Properties_:
if i.Name == 'ProcessId':
return i.Value
Upvotes: 0
Reputation: 2749
with proper indentions it should look like this -
def pid_find(process_name):
pid = []
for proc in psutil.process_iter():
try:
if proc.name() == process_name:
pid.append(proc.pid)
except psutil.AccessDenied:
pass
try:
process = pid[0]
except IndexError:
raise Exception("Process %s not found" % process_name)
print process #prints the correct value
return process # return value
Upvotes: 1