【问题标题】:Output only the ping latency when using the ping command in python在 python 中使用 ping 命令时仅输出 ping 延迟
【发布时间】:2018-02-12 02:15:18
【问题描述】:
import subprocess
ping = subprocess.Popen(["ping", "youtube.com", "-n", "1"], stdout = subprocess.PIPE,stderr = subprocess.PIPE, shell=True)
output = ping.communicate()

上面的代码是我用来在 Python 中 ping 一次服务器的代码,然后我可以将 ping 的结果输出到 python Idle,稍后我将在程序中使用它。但是我遇到的问题是我不希望提供所有输出:

print(output)
# below is the output from this command
(b'\r\nPinging youtube.com [216.58.208.174] with 32 bytes of data:\r\nReply from 216.58.208.174: bytes=32 time=17ms TTL=54\r\n\r\nPing statistics for 216.58.208.174:\r\n    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),\r\nApproximate round trip times in milli-seconds:\r\n    Minimum = 17ms, Maximum = 17ms, Average = 17ms\r\n', b'')

所以,我要总结的问题是,我如何能够简单地捕获:

 time = 17ms

(或当时命令在此处输出的任何内容) 正确方向的一点将不胜感激。谢谢。

【问题讨论】:

    标签: python ping


    【解决方案1】:

    您可以使用正则表达式来提取感兴趣的片段:

    import re
    pattern = r"Average = (\d+\S+)"
    re.findall(pattern, output[0].decode())[0]
    #'17ms'
    

    【讨论】:

    • 这适用于非 Windows 机器吗?还是 ping 命令在 Linux 上的工作方式不同?
    猜你喜欢
    • 2018-09-19
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 2020-10-13
    • 2022-01-15
    • 2010-10-20
    • 2011-02-01
    • 1970-01-01
    相关资源
    最近更新 更多