在 python 中使用 ping 命令时仅输出 ping 延迟

Output only the ping latency when using the ping command in python

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

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

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

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