Python 无需打印到控制台即可获取系统 ping 的输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28769023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get output of system ping without printing to the console
提问by pelos
I want to call ping
from Python and get the output. I tried the following:
我想ping
从 Python调用并获取输出。我尝试了以下方法:
response = os.system("ping "+ "- c")
However, this prints to the console, which I don't want.
但是,这会打印到控制台,这是我不想要的。
PING 10.10.0.100 (10.10.0.100) 56(86) bytes of data.
64 bytes from 10.10.0.100: icmp_seq=1 ttl=63 time=0.713 ms
64 bytes from 10.10.0.100: icmp_seq=2 ttl=63 time=1.15 ms
Is there a way to not print to the console and just get the result?
有没有办法不打印到控制台而只得到结果?
采纳答案by davidism
To get the output of a command, use subprocess.check_output
. It raises an error if the command fails, so surround it in a try
block.
要获取命令的输出,请使用subprocess.check_output
. 如果命令失败,它会引发错误,因此将其括在一个try
块中。
import subprocess
try:
response = subprocess.check_output(
['ping', '-c', '3', '10.10.0.100'],
stderr=subprocess.STDOUT, # get all output
universal_newlines=True # return string not bytes
)
except subprocess.CalledProcessError:
response = None
To use ping
to know whether an address is responding, use its return value, which is 0 for success. subprocess.check_call
will raise and error if the return value is not 0. To suppress output, redirect stdout
and stderr
. With Python 3 you can use subprocess.DEVNULL
rather than opening the null file in a block.
要ping
知道地址是否正在响应,请使用其返回值,成功为 0。 subprocess.check_call
如果返回值不为 0,则会引发并出错。要抑制输出,请重定向stdout
和stderr
。使用 Python 3,您可以使用subprocess.DEVNULL
而不是在块中打开空文件。
import os
import subprocess
with open(os.devnull, 'w') as DEVNULL:
try:
subprocess.check_call(
['ping', '-c', '3', '10.10.0.100'],
stdout=DEVNULL, # suppress output
stderr=DEVNULL
)
is_up = True
except subprocess.CalledProcessError:
is_up = False
In general, use subprocess
calls, which, as the docs describe, are intended to replace os.system
.
一般来说,使用subprocess
调用,正如文档描述的那样,旨在替换os.system
.
回答by Martijn Pieters
If you only need to check if the ping was successful, look at the status code; ping
returns 2
for a failed ping, 0
for a success.
如果只需要检查ping是否成功,看状态码;ping
返回2
失败的 ping,0
成功。
I'd use subprocess.Popen()
(and notsubprocess.check_call()
as that raises an exception when ping
reports the host is down, complicating handling). Redirect stdout
to a pipe so you can read it from Python:
我会使用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'))
You can switch to subprocess.DEVNULL
*if you want to ignore the output; use proc.wait()
to wait for ping
to exit; you can add -q
to have ping
do less work, as it'll produce less output with that switch:
如果你想忽略输出,你可以切换到*;用于等待退出;您可以添加以减少工作量,因为使用该开关会产生更少的输出: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))
In both cases, proc.returncode
can tell you more about why the ping failed, depending on your ping
implementation. See man ping
for details. On OS X the manpage states:
在这两种情况下,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>.
and man sysexits
lists further error codes.
并man sysexits
列出更多错误代码。
The latter form (ignoring the output) can be simplified by using subprocess.call()
, which combines the proc.wait()
with a proc.returncode
return:
后一种形式(忽略输出)可以通过使用 来简化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
is new in Python 3.3; use open(os.devnull, 'wb')
in it's place in older Python versions, making use of the os.devnull
value, e.g.:
*subprocess.DEVNULL
是 Python 3.3 中的新功能;open(os.devnull, 'wb')
在较旧的 Python 版本中使用它,利用os.devnull
value,例如:
status = subprocess.call(
['ping', '-q', '-c', '3', ipaddress],
stdout=open(os.devnull, 'wb'))