【发布时间】:2020-03-09 14:45:11
【问题描述】:
我正在创建一个 Python 程序来每小时监控一次服务器上的进程,以查看它是否可以返回 PID。为此,我创建了一个函数,该函数使用 subprocess 对提交给它的任何名称调用 pgrep -f。如果它返回一个进程,则该函数评估为真;否则返回 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”。
【问题讨论】:
标签: python if-statement subprocess monitoring psutil