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

时间:2018-02-12 02:15:18

标签: python ping

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

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

1 个答案:

答案 0 :(得分:0)

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

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