问题描述
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空闲状态,稍后将在程序中使用。 但是我遇到的问题是我不希望提供所有输出:
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楼
您可以使用正则表达式提取感兴趣的片段:
import re
pattern = r"Average = (\d+\S+)"
re.findall(pattern, output[0].decode())[0]
#'17ms'