Python - 验证变量是否为空

时间:2017-04-03 19:32:03

标签: python

我正在编写一个脚本,通过SSH登录到远程节点,并通过保存pgrep -a <service-name>的输出来检查服务是否已启动,将其存储在变量中并检查该变量是否为UP。 / p>

HOST="172.29.219.110"
COMMAND="pgrep -a haproaxy"
ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
print ( result )
if result == "":
   print ("The service is NOT running")
else:
   print ("The service is running")

如果按原样运行上述内容,我会收到以下回复:

[b'31318 /usr/sbin/haproxy-systemd-wrapper -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid\n', b'31319 /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -Ds\n', b'31320 /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -Ds\n']
The service is running

但是当我pgrep虚假服务时,响应是

[]
The service is running

我已在远程服务器上检查pgrep -a haaaaaaaaa什么都没有回复。但它似乎没有在python中注册为空变量。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您将列表与空字符串等同起来。这就是你的代码失败的原因。对此的正确答案是:

if not result:
  print("The service is not running")