使用python计算urllib响应的平均值

时间:2017-01-05 19:44:11

标签: python api urllib

我想经常计算车辆在5分钟内的速度并计算平均值,如果平均速度超过80则发送电子邮件...

到目前为止,我可以获得每辆车的速度一次并发送电子邮件,问题是不断得到它并计算平均值(每辆车5个速度(每分钟每个)) 我附上了代码,不介意缩进我没有错误。

def check_speed():
    try:
        response = urlopen(full_url)
        outp = response.read()
        print outp
        response2 = urlopen(g_url)
        pasa = json.loads(outp)
        for i in pasa:
            print i['objectno']
            print i['objectname']
            print i['longitude']
            print i['latitude']
            print i['odometer']
            stand=i['standstill']
            print stand


            if stand==0:
                print 'Vehicle Moving'
                if 'speed' in i:

                    print i['speed']
                    veh = i['objectname']

                    speed = i['speed']
                    if int(speed)>=86:
                        speed1=int(speed)


                    #send email
                        print 'over speed'
                        msg = MIMEMultipart()
                        ccaddr = "addr1@gmail.com"
                        toaddr = "addr2@gmail.com"
                        fromaddr = "from@gmail.com"
                        bccadr = "addr3@gmail.com"
                        rcpt = ccaddr.split(",") + bccadr.split(",") + [toaddr]
                        msg = MIMEMultipart('alternative')

                        msg['Subject'] = 'Signaling Overspeed '
                        msg['From'] = fromaddr
                        msg['To'] = toaddr
                        msg['CC'] = ccaddr
                        msg['Bcc'] = bccadr

                        if 'drivername' in i:
                            driver = i['drivername']
                            body = "Vehicle "+veh+" Driven by "+driver+" is moving on "+str(speed)
                        else:
                            body = "Vehicle " + veh +" is moving on " + str(speed)
                        msg.attach(MIMEText(body, 'plain'))
                        server = smtplib.SMTP('smtp.gmail.com', 587)
                        server.starttls()
                        server.login(fromaddr, "pwd")
                        text = msg.as_string()
                        server.sendmail(fromaddr, rcpt, text)
                        server.quit()

                    elif speed==i['speed']<50:
                        print 'traffic jam'

            elif stand==1:

                print 'Vehicle not Moving'





    except URLError, e:
        print 'Got an error code:', e
    time.sleep(300)

#loop that get the speed of vehicles
while True:
    check_speed()

1 个答案:

答案 0 :(得分:0)

您似乎需要存储计算最后一个值的时间以及该值的值。为此,您可以:

  • 使用数据库(上面可能不需要,因为这非常简单)。
  • 使用可能将时间/速度存储为元组的类,您可以将所有内容保存在内存中,例如[(time1, speed1), (time2, speed2), ...]
  • 最后,您可以在time, speed函数中返回check_speed()元组,并将其存储在while循环的列表中。例如:

my_values = []
while True:
    time, speed = check_speed()
    my_values.append((time, speed))

通过上述结构,可以很容易地计算出最后一分钟,一小时,一天等的平均值。