我正在创建一个Python程序来每小时监视一次服务器上的进程,以查看它是否可以返回PID。为此,我制作了一个函数,该函数使用子进程对提交给它的任何名称调用pgrep -f。如果返回进程,则该函数的值为true;否则为false。否则,它返回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
函数本身是否为假。
不是,因为它是一个函数。