遍历进程列表以检查Python子进程是否存在PID

2024-05-19 03:20:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个Python程序,每小时监视一次服务器上的进程,看看它是否可以返回PID。为此,我创建了一个函数,该函数使用subprocess对提交给它的任何名称调用pgrep-f。如果返回一个进程,函数的计算结果为true;否则,它将返回false

import subprocess
import psutil


def check_essentials(name):
    child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
    response = child.communicate()[0]
    pid = response.split()
    if len(pid) == 0:
        print("unable to find PID")
        return False
    else:
        print("PID is %s" % pid)
        return True

essentialApps = ['ProfileService','aflaf']
sendEmail=False

for x in essentialApps:
    check_essentials(x)
    if check_essentials == False:
        print("Unable to find PID for %s. Sending email alert" % x)
        sendEmail = True
    else:
        print("Found PID for %s" % x)

然后,我设置了一个for循环,让它遍历一个进程名列表(essentialApps),并查看它是否可以为它们返回任何内容。否则,sendEmail将设置为true

然而,在测试过程中,我发现无论应用程序是否存在,else语句总是被调用。当我调用这个程序(python alert.py)时,我得到以下输出:

PID is [b'11111']
Found PID for ProfileService 
unable to find PID #This is expected
Found PID for aflaf #This should be "Unable to find PID for aflaf"

我相信这很简单,但是有人能告诉我为什么它不能正确地评估check_-essential吗

另外,psutil是否也可以这样做?我读到这应该在子进程上使用,但我找不到任何方法来专门模拟pgrep -f nameps -aux | grep name。这很重要,因为我有多个Java应用程序在机器上运行,psutil似乎看到的程序名总是“Java”,而不是“ProfileService”


Tags: to函数name程序falsefor进程check
2条回答

您没有使用函数的结果,而是检查check_essentials函数本身是否为False

它不是,因为它是一个函数

您需要向您提供check_essentials的结果,在您的条件下,check_essentials始终是True,因为它是Python对象:

for x in essentialApps:
    check_result = check_essentials(x)
    if check_result == False:

相关问题 更多 >

    热门问题