2016-10-13 19 views
0

我while循環時,第二個條件匹配,第一個被忽略僅僅結束,我不知道我做錯了雖然僅環響應第二個條件

while (response !=0) or (cont != 5): 
    response = os.system("ping -c 2 " + hostname) 
    cont=cont+1 
    print cont 
    print response 
+2

只要_either_條件滿足,循環就會繼續。如果您希望在一種情況失敗時立即結束,請使用'and'而不是'或'。 – khelwood

+0

請使用'subprocess.check_output'或類似的函數來調用Shell腳本而不是'os.system'。這樣你可以更好地控制輸出。請參閱:https://docs.python.org/2/library/subprocess.html#subprocess-replacements –

+0

問題是使用or運算符而不是和,謝謝! –

回答

0

隨着subprocess.call

import subprocess 

for count in range(5); 
    response = subprocess.call(["ping", "-c", "2", hostname]) 
    if not response: 
     break 

不想一次迭代與rangexrange

0

更改orand。當它檢查第一個條件時,如果這是錯誤的而第二個條件是真的,那麼整個條件將是真實的。這意味着要麼第一個條件成立,要麼第二個條件成立。

While (false or true) will be while (true) 

要檢查兩個條件,你應該使用and。它檢查這兩個條件應爲true表達式爲true

while (false and true) will be while (false) 

while (response !=0) and (cont != 5): 
    response = os.system("ping -c 2 " + hostname) 
    cont=cont+1 
    print cont 
    print response