I want to constantly calculate the speed of vehicles during 5 min and calculate the average, if the average speed is more than 80 send an email...
so far i can get the speed per vehicle once and send email,the issue is continuously getting it and calculating the average(5 speeds(each per min) per vehicle)
I have attached the code, dont mind the indentation i have no errors.
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()
It seems like you need to store the time that the last value was calculated and what that value was. For doing this, you can either:
Use a database (probably not needed in the above, since this is pretty straightforward).
Use a class with perhaps the time/speed stored as a tuple where you can keep everything in memory, such as [(time1, speed1), (time2, speed2), ...].
Finally, you could return a time, speed tuple in your check_speed() function and store it in a list in the while loop. For example:
.
my_values = []
while True:
time, speed = check_speed()
my_values.append((time, speed))
With the above structure it would be easy to calculate averages over the last minute, hour, day, etc.
Related
Basically I'm creating a program to help with my work. It will send emails to people in an excel list and move down to the next first name and email address in the list until it's done. Heres the code so far
`#AutoMail Version 2
#Goal of new version is to run on any computer. With minimal or no mouse and keyboard input
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#Random Variables
sender_address = str(input("Please enter your email address!: "))
sender_pass = str(input("Please enter your email password (No data is stored anywhere!): "))
count = 0
#This prompts user to input the file path of their CSV file.
file_path = "C:/Users/Spring/Documents/test_book_py.csv" #Change to input later!!!!!!
df = pd.read_csv(file_path, usecols=['First Name', 'Email Address'])
amount = int(input("How many emails would you like to send? "))
#Important Variables
cell_value = 0 #Which cell the info is coming from
#Cell Varialbes
name_cell = df["First Name"].values[cell_value]
email_cell = df["Email Address"].values[cell_value]
#Gmail info Variables
receiver_address = email_cell
email_subj = "This is a test subject"
email_body = "Hello " + name_cell + ",\n\nThis is a test body"
message = MIMEMultipart()
#Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
#Emailing Process Start
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = email_subj
message.attach(MIMEText(email_body, 'plain'))
text = message.as_string()
#Email sending
while count < amount:
session.sendmail(sender_address, receiver_address, text)
cell_value = cell_value + 1
count = count + 1
print(cell_value)`
I've tried every fix I could find online for variables not updating. When I print the "cell_value" varible it prints with the updated value however the other lines in the code specifically lines 21 and 22 use that variable and they aren't using the updated varible so it is always at a constant 0 value when it should be cell_value + 1 every time the loop repeats. Is there a different way I should loop the variable updating? I need it to change that value by +1 every time so that it continues to move down the list. Keep in mind that I am a huge beginner so my code probably looks very confusing.
The issue is updating cell_value doesn't automatically updates all the data that was calculated with cell_value's old value. Once "Hello " + name_cell + ",\n\nThis is a test body" evaluates, for example, the resulting string has no relation to name_cell, and wan't change when name_cell changes. If you want that string to change when name_cell changes, you need to rerun the code that created that string.
For your case here, it looks like you could just loop over the latter half of the code. The closest to what you already have would be:
# i instead of cell_value for clarity
for i in range(amount):
name_cell = df["First Name"].values[cell_value]
email_cell = df["Email Address"].values[cell_value]
receiver_address = email_cell
email_subj = "This is a test subject"
email_body = "Hello " + name_cell + ",\n\nThis is a test body"
message = MIMEMultipart()
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = email_subj
message.attach(MIMEText(email_body, 'plain'))
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
Arguably, it would be may be considered more idiomatic to zip the two .values objects that you're looping over, then islice amount-many elements from that, but I think this is cleaner.
I have four python functions that I am using to send mail. If the program does one thing, it mails a set of results to a multiple recipients, if it does another thing, a separate function mails the results to one recipient.
def smail(to,sub,body):
addr_from = 'alert#example.com'
msg = MIMEMultipart()
msg['From'] = addr_from
msg['To'] = to
msg['Subject'] = sub
msg.attach(body)
s = smtplib.SMTP('webmail.example.com')
s.sendmail(addr_from, [to], msg.as_string())
s.quit()
def email_format2(results):
text = ""
text += 'The following applications in <environment> are non-compliant\n'
text += '<br>'
text += 'Here are there names and locations. Please inform the developer.'
text += '<br>'
text += '<br>'
table = pd.DataFrame.from_records(results)
table_str = table.to_html()
text += "%s" % table_str
return text
def mail_results_aq(results):
body = email_format2(results)
msg = MIMEText(body, 'html')
sub = "Placeholder subject"
to = 'email1#example.com, email2#example.com, email3#example.com'
smail(to, sub, msg)
def mail_results_prd(results):
body = email_format2(results)
msg = MIMEText(body, 'html')
sub = "Placeholder subject"
to = 'email4#example.com'
smail(to, sub, msg)
The mail_results_aq function will only email results to the first recipient (email1#example.com).
In other questions similar to this one, I've seen a the recipients being entered into a list i.e
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me#example.com'
recipients = ['john.doe#example.com', 'john.smith#example.co.uk']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())
However, this use case only seems to work when used in the same function. How can I implement this feature across the four functions I have above?
Thanks in advance!
I wrote a script to send an email if the values match a certain criteria. I'm wanting to send 1 email instead of multiple emails upon every check. I thought I can mitigate by throwing in another function but I can't figure out how to do it. Any ideas on how to accomplish this?
import csv, requests, xmltodict, smtplib, email.utils
from email.mime.text import MIMEText
def sendEmail(host, value, devicename):
# Create the message
msg = MIMEText('This is the body of the message.')
msg['To'] = email.utils.formataddr(('Recipient', 'XXXXXX'))
msg['From'] = email.utils.formataddr(('Author', 'XXXXX'))
msg['Subject'] = 'Simple test message'
server = smtplib.SMTP('XXXXXXX')
server.set_debuglevel(True) # show communication with the server
try:
server.sendmail('XXXXXX', ['XXXXXX'], msg.as_string())
finally:
server.quit()
def check(hostIP, value):
xml = """<?xml version="1.0" encoding="iso-8859-1"?>"""
headers = {'Content-Type': 'application/xml'}
response = requests.post('http://' + hostIP + '/RPC2', data=xml, headers=headers).text
doc = xmltodict.parse(response)
uptime = str(doc['response'])
maxtime = '300'
time = str(uptimeValue)
day = time // (24 * 3600)
if day >= maxtime:
print 'it is'
sendEmail(str(hostIP), str(value), str(devicename))
else:
print "it is not!"
def main():
try:
with open('list.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
check(row['Host'], row['Value'])
except Exception as error:
print ValueError("Could not properly read the csv file")
sys.exit(0)
if __name__ == "__main__":
main()
Replace
def sendEmail(message):
and
if day >= maxtime:
print 'it is'
return (str(hostIP), str(value), str(devicename))
and
device_list = []
for row in reader:
result = check(row['Host'], row['Value'])
if result:
device_list.append(', '.join(result))
sendEmail('\n'.join(device_list))
Instead of using check to send the email, use it to add an item to go into the message body, probably in an array or dictionary. Then, after you are done processing your file, you can use that collected information to build the body of your email to give to a single call to sendEmail.
That means you don't call sendEmail from inside of check; you call it from main once you are done with the file.
I've written a Python script to automatically send some information to my friends. I used SMTPlib, it works well if I only sent to me or one additional email.
When I try to send to 17 emails, (including my sender email), then it shows in sent mail on web-based Gmail. I saw that the mail was sent but I didn't receive it. Only the first recipient received the email.
If I reply to all from that mail, then everyone got only that reply.
I can't figure out why they didn't receive it when I sent it from script, I ask my friend check spam, but she didn't find anything.
This is my code:
#!/usr/bin/env python
import smtplib
import csv
from datetime import datetime, timedelta
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587
sender = 'MYBOT#gmail.com'
password = None
with open('pass', 'rt') as f:
password = f.read().strip('\n')
def send_mail(recipient, subject, body):
"""
Send happy bithday mail
"""
headers = ["From: " + sender,
"Subject: " + subject,
"To: " + recipient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
smtp = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
smtp.ehlo()
smtp.starttls()
smtp.ehlo
smtp.login(sender, password)
body = "" + body +""
smtp.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
print "Sent to ",
print recipient
smtp.quit()
def send_happybirthday(recipient):
body = """Happy birthday to you!
\n<br/>From C2k8pro with love
"""
subject ='[BirthReminder] Happy birthday to you! from C2k8pro'
send_mail(recipient, subject, body)
def send_notification(all_mails, names):
body = """Tomorrow is birthday of %s""" % names
send_mail(all_mails, body, body)
def test_send_mail():
notify_body = """Tomorrow is birthday of """
recipients = ['MYBOT#gmail.com']
today = datetime.now()
format = "%d-%m-%Y"
print today
today_in_str = datetime.strftime(today, format)
def read_csv():
FILENAME = 'mails.csv'
reader = csv.reader(open(FILENAME, 'rt'), delimiter=',')
today = datetime.now()
one_day = timedelta(days=1)
tomorrow = today + one_day
all_mails = []
str_format = "%d/%m"
str_today = today.strftime(str_format)
str_tomorrow = tomorrow.strftime(str_format)
print 'Today is ', str_today
tomorrow_birth = []
for row in reader:
name = row[1].strip()
dob = row[2]
dmy = dob.split("/")
mail = row[3]
all_mails.append(mail)
#TODO fix dob with only 1 digit
birth_date = dmy[0] + "/" + dmy[1]
if str_today == birth_date:
print 'Happy birthday %s' % name
try:
send_happybirthday(mail)
except Exception, e:
print e
elif str_tomorrow == birth_date:
tomorrow_birth.append(name)
print "Tomorrow is %s's birthday" % name
# Remove empty string
all_mails = filter(None, all_mails)
print 'All mails: ', len(all_mails)
str_all_mails = ', '.join(all_mails)
if tomorrow_birth:
all_tomorrow = ', '.join(tomorrow_birth)
send_notification(str_all_mails, all_tomorrow)
def main():
read_csv()
if __name__ == "__main__":
main()
Can anyone explain this. Thanks!
I found solution from here
Send Email to multiple recipients from .txt file with Python smtplib
I passed a string contain all recipients separated by comma to msg['To'] and sendmail().
It's true for msg['To'] but with sendmail, I have to use a list.
Here's my script with the personal bits scrubbed.
import urllib, urllib2, cookielib
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
resp3 = opener.open('https://www.mynexia.com/login')
resp4 = resp3.read().split('input name=\"authenticity_token\" type=\"hidden\" value=\"')
resp5 = resp4[1].split('\" /></div>')
login = 'website username'
password = 'website pass'
authenticity_token = resp5
login_data = urllib.urlencode({'login' : login, 'password' : password,'authenticity_token' : authenticity_token})
opener.open('https://www.mynexia.com/session', login_data)
resp = opener.open('https://www.mynexia.com/houses/ourstaticaccountpage/climate')
resp1 = resp.read().split('<div class=\"temperature\"><span>')
resp2 = resp1[1].split('</span></div>')
int(resp2[0])
if resp2[0] > 75:
import smtplib
import string
SUBJECT = "Temperature is rising!"
TO = "helpdesk#whoever.blah"
FROM = "me#gmail.com"
text = "Temperature is " + resp2[0]
BODY = string.join((
"From: %s" % FROM,
"To: %s" % TO,
"Subject: %s" % SUBJECT,
"",
text
), "\r\n")
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login("me#gmail.com", "gmailpass")
server.sendmail(FROM, [TO], BODY)
elif resp2[0] <= 75:
import smtplib
import string
SUBJECT = "Temperature is ok"
TO = "helpdesk#whereever.blah"
FROM = "me#gmail.com"
text = "Temperature is " + resp2[0]
BODY = string.join((
"From: %s" % FROM,
"To: %s" % TO,
"Subject: %s" % SUBJECT,
"",
text
), "\r\n")
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login("me#gmail.com", "gmailpass")
server.sendmail(FROM, [TO], BODY)
It works fine, except it always evaluates resp2[0] as > 75 no matter what its value is. The point of this script is to alert me when a room that some sensitive machines are running in gets warmer than 75 degrees. The website I'm scraping from only allows you to send alerts if it gets over 90. By then I'm at risk of machines going down, so I wanted to alert myself earlier. I'm going to run it with a cronjob every 15 minutes, and once I get the if-else statement working right, I'm just going to have <= dump to a log file instead of sending out an "Everything is a-ok alert." Any suggestions on why I fail at basic math? Is there a problem with my int(resp2[0])? Is it not base 10 by default?
resp2 is a list of strings. A string is greater than an integer. You need to call int on it before comparison.
Actually, I see that you are calling int - but you're not doing anything with the result. Doing int(resp2[0]) doesn't convert the contents of resp2[0] to an integer. It simply returns the converted value. If you don't assign it to anything, it just gets thrown away. You need to assign it to a new variable, and then use that variable in your if statements.
Have you tried logging the value of resp2[0] to see what values you are getting? A simple
print resp2[0]
while debugging...