使用Python获取Ping延迟时间失败,正则匹配返回空列表求助
问题原因及解决方案
核心原因
正则表达式不匹配系统语言的ping输出:
你用的正则temps=[0-9]+ms是法语等非中文/英文系统下的ping输出格式。如果你的Windows系统是中文,ping的延迟字段为时间=[0-9]+ms;如果是英文系统则是time=[0-9]+ms,自然匹配不到目标内容。输出未正确解码:
subprocess.communicate()[0]返回的是bytes类型数据,直接用str(ping)转换会得到带b'...'前缀的字符串,内容包含转义符,导致正则无法识别有效字段。
修正后的代码
中文系统版本
import subprocess import re # 执行ping命令,同时捕获标准输出和错误输出 p = subprocess.Popen(["ping.exe", "8.8.8.8"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) ping_output, _ = p.communicate() # Windows cmd默认编码为gbk,解码为字符串 ping_str = ping_output.decode("gbk") # 匹配中文系统下的延迟字段 timestr = re.compile(r"时间=(\d+)ms").findall(ping_str) print(timestr)
英文系统版本
import subprocess import re p = subprocess.Popen(["ping.exe", "8.8.8.8"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) ping_output, _ = p.communicate() # 英文系统用utf-8解码 ping_str = ping_output.decode("utf-8") # 匹配英文系统下的延迟字段 timestr = re.compile(r"time=(\d+)ms").findall(ping_str) print(timestr)
额外说明
- 若不确定系统编码,可先打印
ping_str查看实际输出内容,再调整解码方式和正则表达式。 - 加入
stderr=subprocess.PIPE可捕获错误输出,避免命令执行出错时程序阻塞。
内容的提问来源于stack exchange,提问作者Chris Ze Third
相关产品推荐
相关产品推荐

