我想经常计算车辆在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()
答案 0 :(得分:0)
您似乎需要存储计算最后一个值的时间以及该值的值。为此,您可以:
[(time1, speed1), (time2, speed2), ...]
。time, speed
函数中返回check_speed()
元组,并将其存储在while循环的列表中。例如:
my_values = []
while True:
time, speed = check_speed()
my_values.append((time, speed))
通过上述结构,可以很容易地计算出最后一分钟,一小时,一天等的平均值。