在Python中返回ping测试结果

时间:2013-07-19 23:47:03

标签: python networking tcp latency

我正在尝试在Windows上打印ping测试结果。但是,当网站超时时会发生以下错误:

IndexError:列表索引超出范围。

显然,它正在寻找结果,但是当它超时的时候我怎么能说“网站不可用”?

try:
    ping = subprocess.Popen(["ping", "-n", "5", website], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, error = ping.communicate()

    minimum = int(re.findall(r"Minimum = (\d+)", out)[0])
    maximum = int(re.findall(r"Maximum = (\d+)", out)[0])
    average = int(re.findall(r"Average = (\d+)", out)[0])
    packet = int(re.findall(r"Lost = (\d+)", out)[0])

    if packet > 1:
        packet = 5 / packet * 100

    except subprocess.CalledProcessError:
        print "Couldn't get a ping"

1 个答案:

答案 0 :(得分:3)

之类的东西

修改:试试这个:

import re
import subprocess
website = "google.com"
try:
    ping = subprocess.Popen(["ping", "-n", "-c 5", website], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, error = ping.communicate()
    if out:
        try:
            minimum = int(re.findall(r"Minimum = (\d+)", out)[0])
            maximum = int(re.findall(r"Maximum = (\d+)", out)[0])
            average = int(re.findall(r"Average = (\d+)", out)[0])
            packet = int(re.findall(r"Lost = (\d+)", out)[0])
            if packet > 1:
                packet = 5 / packet * 100
        except:
            print "no data for one of minimum,maximum,average,packet"
    else:
        print 'No ping'

except subprocess.CalledProcessError:
    print "Couldn't get a ping"