0

我有一个函数应该使用 psutil 返回给定进程的进程 ID,但由于某种原因它不返回任何内容。

打印所需的变量会显示正确的值。我想我做错了什么。

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
4

4 回答 4

1

有适当的缩进它应该看起来像这样 -

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
于 2015-10-27T13:48:22.340 回答
0

我想我找到了问题所在。该功能工作正常,但我没有正确调试以检查该功能是否有效:

这就是我尝试的方式:

函数位于文件functions.py文件中
我在test.py文件中调用函数,如下所示:

import functions
def debug
   functions.pid_find("chrome.exe) 

if __name__ == "__main__":
    debug()

但是如果我将函数放入一个变量中,我应该能够存储结果并进一步使用它:

import functions
def debug(proc):
    pid = functions.pid_find(proc)
    print pid #shows that pid has the correct value
于 2015-10-27T15:18:12.083 回答
0

我只是尝试测试您的代码。这是有效的,除了这个:

if proc.name() == process_name:

必须替换为:

if proc.name == process_name:

进行一些简化,但具有您的代码精神:

   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")
于 2015-10-27T14:07:26.477 回答
0

无需迭代即可使用 wmi 查询完成:

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
于 2015-10-27T13:56:30.040 回答