2014-02-06 52 views
0

我想通過python腳本ping主機,並捕獲ping的輸出和退出代碼。爲了這個,我想出了下面的Python代碼片段:Python運行ping並獲取退出代碼

ping_command = "ping -c 5 -n -W 4 " + IP 
ping_process = os.popen(ping_command) 
ping_output = ping_process.read() 
exit_code_ping = ping_process.close() 
exit_code = os.WEXITSTATUS(exit_code_ping) 
print ping_output 
print exit_code 

,我已經發現,如果給定IP的主機已關閉或者它無法訪問的代碼工作。然而,如果主機是它給了我:

exit_code = os.WEXITSTATUS(exit_code_ping) 
TypeError: an integer is required 

因爲我是非常初學者在python我不知道這裏的問題是什麼。

問題:我在做什麼錯誤,爲什麼這個東西不能正常工作...最重要的是,我怎麼能使它工作。

回答

3

順便說一句,你可以通過把內部解決您的片段try塊,當成功出口代碼爲無:

try: 
    exit_code = os.WEXITSTATUS(exit_code_ping) 
    print exit_code 
except Exception as er: 
    print 'Error: ', er 

print ping_output 

更好的方法是使用子過程:

import subprocess 

IP = '8.8.8.100' 
ping_command = "ping -c 5 -n -W 4 " + IP 

(output, error) = subprocess.Popen(ping_command, 
            stdout=subprocess.PIPE, 
            stderr=subprocess.PIPE, 
            shell=True).communicate() 

print output, error