2014-07-17 85 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子進程。