1

我正在尝试在 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"
4

1 回答 1

3

What about something like

edit : try this:

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"
于 2013-07-19T23:58:54.130 回答