如果只需要检查ping是否成功,查看状态码; ping 返回 2 表示 ping 失败,0 表示成功。
我会使用subprocess.Popen()(并且不 subprocess.check_call() 因为当ping 报告主机已关闭时会引发异常,从而使处理复杂化)。将 stdout 重定向到管道,以便您可以从 Python 中读取它:
ipaddress = '198.252.206.140' # guess who
proc = subprocess.Popen(
['ping', '-c', '3', ipaddress],
stdout=subprocess.PIPE)
stdout, stderr = proc.communicate()
if proc.returncode == 0:
print('{} is UP'.format(ipaddress))
print('ping output:')
print(stdout.decode('ASCII'))
如果要忽略输出,可以切换到subprocess.DEVNULL*;使用proc.wait() 等待ping 退出;您可以添加 -q 以使 ping 做更少的工作,因为使用该开关会产生更少的输出:
proc = subprocess.Popen(
['ping', '-q', '-c', '3', ipaddress],
stdout=subprocess.DEVNULL)
proc.wait()
if proc.returncode == 0:
print('{} is UP'.format(ipaddress))
在这两种情况下,proc.returncode 可以告诉您更多关于 ping 失败的原因,具体取决于您的 ping 实施。有关详细信息,请参阅man ping。在 OS X 上,联机帮助页指出:
EXIT STATUS
The ping utility exits with one of the following values:
0 At least one response was heard from the specified host.
2 The transmission was successful but no responses were received.
any other value
An error occurred. These values are defined in <sysexits.h>.
和man sysexits 列出更多错误代码。
后一种形式(忽略输出)可以通过使用subprocess.call() 来简化,它将proc.wait() 与proc.returncode 返回:
status = subprocess.call(
['ping', '-q', '-c', '3', ipaddress],
stdout=subprocess.DEVNULL)
if status == 0:
print('{} is UP'.format(ipaddress))
*subprocess.DEVNULL 在 Python 3.3 中是新的;在旧 Python 版本中使用open(os.devnull, 'wb'),利用os.devnull value,例如:
status = subprocess.call(
['ping', '-q', '-c', '3', ipaddress],
stdout=open(os.devnull, 'wb'))