2014-07-17 50 views
0

我想从下面的代码中获取数字值。当我“打印”出价值时,我会得到一个数字“1”。然而,当它进入“if”语句时,我总是将“closed”作为“STORE”中的存储变量。代码的第三行用于删除回车。使用子进程隐藏字符.Popen

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语句正确显示,我确实有正确的凹痕,如果我给你的变量它的工作)

if CLOSED_OUTPUT == 1: 
    STORE = "open" 
else: 
    STORE = "closed" 

print ("The store is %s." % (STORE)) 

回答

2

CLOSED_OUTPUT是一个字符串,所以它会从来没有比等于整数1

你可以尝试

if CLOSED_OUTPUT == '1': 

或者,如果y你期望结果通常是一个整数,在使用它之前将它转换为一个整数。

+0

谢谢科林,这解决了我的问题。 –

0
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()忽略空格,如'\n'即,你不需要做更换。你也可以用Python重新实现grep .. | awkparamiko(Python ssh库)允许你通过ssh运行远程命令,而不需要运行ssh子进程。