我正在创建一个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 name
或ps -aux | grep name
。这很重要,因为我有多个Java应用程序在机器上运行,psutil似乎看到的程序名总是“Java”,而不是“ProfileService”
您没有使用函数的结果,而是检查
check_essentials
函数本身是否为False
它不是,因为它是一个函数
您需要向您提供
check_essentials
的结果,在您的条件下,check_essentials
始终是True
,因为它是Python对象:相关问题 更多 >
编程相关推荐