我想使用Python在Windows下解析ping
命令的输出。特别是最小,最大和平均RTT。
我有以下代码:
from sys import platform
import re
if platform == "linux" or platform == "darwin":
command=["ping", "-c", "3", "-i", "0.2", IP]
timeout=0.5
else:
command=["ping", "-n", "1", IP]
timeout=0.2 proc=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
try:
[out, err]=proc.communicate(timeout=timeout)
if proc.returncode == 0:
if platform == "linux" or platform == "darwin":
# rtt min/avg/max/mdev = 578.263/917.875/1013.707/132.095 ms
avgRTT=re.search("rtt min/avg/max/mdev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)", str(out)).group(2)
else:
# Approximate round trip times in milli-seconds: Minimum = 63ms, Maximum = 64ms, Average = 63ms
avgRTT=re.search("Minimum = (\d+), Maximum = (\d+), Average = (\d+)", str(out))
print(avgRTT.group())
except subprocess.TimeoutExpired:
proc.kill()
它在GNU / linux和mac os X下运行良好,而在Windows下则不运行。我也尝试使用信息here,但没有成功。
答案 0 :(得分:1)
我已经采用了您的代码,只是做了一些小改动。 ms
的正则表达式中缺少windows
,而只需要添加一些包含和空格(可能部分是由于StackOverflow格式所致)。现在,它可以在我的windows 7.0
框中运行了。您应该只能够复制/粘贴/按一下就可以得到想要的结果:)
from sys import platform
import subprocess
import re
IP = "127.0.0.1"
if platform == "linux" or platform == "darwin":
command=["ping", "-c", "3", "-i", "0.2", IP]
timeout=0.5
else:
command=["ping", "-n", "1", IP]
timeout=0.2
proc=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
try:
[out, err]=proc.communicate(timeout=timeout)
if proc.returncode == 0:
if platform == "linux" or platform == "darwin":
# rtt min/avg/max/mdev = 578.263/917.875/1013.707/132.095 ms
avgRTT=re.search("rtt min/avg/max/mdev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)", str(out)).group(2)
else:
# Approximate round trip times in milli-seconds: Minimum = 63ms, Maximum = 64ms, Average = 63ms
avgRTT=re.search("Minimum = (\d+)ms, Maximum = (\d+)ms, Average = (\d+)", str(out))
print(avgRTT.group())
except subprocess.TimeoutExpired:
proc.kill()
输出: