Python 使用subprocess.Popen隐藏的字符
我试图从下面的代码中获取一个数值。当我“打印”出值时,我得到一个数字“1”。然而,当它转到“if”语句时,我总是将“closed”作为“STORE”中存储的变量。代码的第三行用于删除回车符Python 使用subprocess.Popen隐藏的字符,python,variables,subprocess,popen,Python,Variables,Subprocess,Popen,我试图从下面的代码中获取一个数值。当我“打印”出值时,我得到一个数字“1”。然而,当它转到“if”语句时,我总是将“closed”作为“STORE”中存储的变量。代码的第三行用于删除回车符 CLOSED = subprocess.Popen( [ "ssh", "hostname", "/usr/blaine/store_status | grep 00 | awk \{\'print $5\'\}" ], stdout=s
CLOSED = subprocess.Popen(
[
"ssh",
"hostname",
"/usr/blaine/store_status | grep 00 | awk \{\'print $5\'\}"
],
stdout=subprocess.PIPE
)
CLOSED_OUTPUT = CLOSED.stdout.read()
CLOSED_OUTPUT = CLOSED_OUTPUT.replace('\n','')
(很难让if语句正确地显示,我确实有正确的缩进,如果我分配变量,它确实有效)
CLOSED_输出是一个字符串,因此它永远不会与整数1进行比较 你可以试试
if CLOSED_OUTPUT == '1':
或者,如果您希望结果通常是整数,请在使用它之前将其转换为整数
from subprocess import check_output
output = check_output(["ssh", "hostname",
"/usr/blaine/store_status | grep 00 | awk \{'print $5'\}"])
try:
value = int(output)
except ValueError:
opened = False
else:
opened = (value == 1)
print("The store is {}.".format("open" if opened else "closed"))
int()。您还可以重新实现grepawk
Python中的一部分paramiko
(Python ssh库)允许您通过ssh运行远程命令,而无需运行ssh
子进程
from subprocess import check_output
output = check_output(["ssh", "hostname",
"/usr/blaine/store_status | grep 00 | awk \{'print $5'\}"])
try:
value = int(output)
except ValueError:
opened = False
else:
opened = (value == 1)
print("The store is {}.".format("open" if opened else "closed"))