这里使用的是最简易的方式,使用python的子进程管理模块,调用系统的ping命令,代码如下:
import subprocess
import re
p = subprocess.Popen(["ping.exe", 'google.com'],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = True)
out = p.stdout.read()
regex = re.compile("Minimum = (\d+)ms, Maximum = (\d+)ms, Average = (\d+)ms", re.IGNORECASE)
print regex.findall(out)
import re
p = subprocess.Popen(["ping.exe", 'google.com'],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = True)
out = p.stdout.read()
regex = re.compile("Minimum = (\d+)ms, Maximum = (\d+)ms, Average = (\d+)ms", re.IGNORECASE)
print regex.findall(out)
ping的结果用正则取出来。
该代码在xp+python2.5上测试通过,如果是linux系统,需要修改正则,因为linux上的ping的返回结果和windows的不太一样。该短代码的缺点是调用的时候,由于要等待ping命令返回,所以界面会假死,可以考虑开单独的线程处理。