【问题标题】:How to save ping output in python [duplicate]如何在python中保存ping输出[重复]
【发布时间】:2019-09-05 15:08:52
【问题描述】:

我有以下代码返回设备的 ping 状态:

def ping_check(hostname):
    response = os.system("ping -c 3 " + hostname)
    if response == 0:
        pingstatus = "Online"
    else:
        pingstatus = "Offline"
    return pingstatus

效果很好并且按预期工作。但是,我想将 ping 输出保存到一个变量中,但我不知道该怎么做。

现在的输出如下所示:

>>> hostname = "google.com"
>>> op = os.system("ping -c 3 " + hostname)
PING google.com (172.217.7.206) 56(84) bytes of data.
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=1 ttl=48 time=1.56 ms
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=2 ttl=48 time=1.57 ms
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=3 ttl=48 time=1.52 ms

--- google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2012ms
rtt min/avg/max/mdev = 1.526/1.552/1.572/0.049 ms
>>> 

我想将 ping 的实际输出保存到一个变量中,这样我就可以将它放入一些东西中以供以后使用。非常感谢任何帮助。

【问题讨论】:

  • 看看subprocess模块
  • 您无法保存来自os.system() 的输出,因为您的程序实际上从未收到它 - 它直接进入您的终端。正如 dcg 所说,使用subprocess

标签: python ping


【解决方案1】:

你可以使用subprocess.check_output:

import subprocess
output = subprocess.check_output(["ping","-c","3",hostname])

注意返回值的类型是bytes

【讨论】:

    猜你喜欢
    • 2015-12-28
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2023-03-03
    • 2022-01-26
    • 2013-09-12
    • 2021-06-28
    相关资源
    最近更新 更多