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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:43:20  来源:igfitidea点击:

Get output of system ping without printing to the console

python

提问by pelos

I want to call pingfrom 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 tryblock.

要获取命令的输出,请使用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 pingto know whether an address is responding, use its return value, which is 0 for success. subprocess.check_callwill raise and error if the return value is not 0. To suppress output, redirect stdoutand stderr. With Python 3 you can use subprocess.DEVNULLrather than opening the null file in a block.

ping知道地址是否正在响应,请使用其返回值,成功为 0。 subprocess.check_call如果返回值不为 0,则会引发并出错。要抑制输出,请重定向stdoutstderr。使用 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 subprocesscalls, 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; pingreturns 2for a failed ping, 0for a success.

如果只需要检查ping是否成功,看状态码;ping返回2失败的 ping,0成功。

I'd use subprocess.Popen()(and notsubprocess.check_call()as that raises an exception when pingreports the host is down, complicating handling). Redirect stdoutto 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 pingto exit; you can add -qto have pingdo less work, as it'll produce less output with that switch:

如果你想忽略输出,你可以切换到*;用于等待退出;您可以添加以减少工作量,因为使用该开关会产生更少的输出:subprocess.DEVNULLproc.wait()ping-qping

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.returncodecan tell you more about why the ping failed, depending on your pingimplementation. See man pingfor 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 sysexitslists 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.returncodereturn:

后一种形式(忽略输出)可以通过使用 来简化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.DEVNULLis new in Python 3.3; use open(os.devnull, 'wb')in it's place in older Python versions, making use of the os.devnullvalue, e.g.:

*subprocess.DEVNULL是 Python 3.3 中的新功能;open(os.devnull, 'wb')在较旧的 Python 版本中使用它,利用os.devnullvalue,例如:

status = subprocess.call(
    ['ping', '-q', '-c', '3', ipaddress],
    stdout=open(os.devnull, 'wb'))