0
這是我簡單的例子:如何用Python捕捉ping錯誤?
import subprocess
cmd = 'ping something.local -c 1'
tail = 'tail -n 3'
ping = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE)
tail = subprocess.Popen(tail.split(' '), stdin=ping.stdout, stdout=subprocess.PIPE)
ping.stdout.close()
out, err = tail.communicate()
print 'Print values:'
print out
print err
這裏是腳本輸出的例子:
[~/python]$ python ping_stats.py
ping: cannot resolve tpeo.local: Unknown host
Print values:
None
所以,我的變量out
和err
是「空」的,但我需要一個ping: cannot resolve tpeo.local: Unknown host
錯誤信息。我怎麼能得到它?
用途使用os.system代替POPEN。然後檢查響應代碼 –
那麼,是不是可以用subprocess.Popen做? –