Link to home
Start Free TrialLog in
Avatar of dynamicOne
dynamicOne

asked on

Write Output to a Text File

I have this script that is running great. I would like to log an entry every time the door is opened and closed with a time stamp. Where would I start? The script is below.

Thanks!


#! /usr/bin/env python
import commands
import smtplib
from email.MIMEText import MIMEText

ser = 'gpio read 1'  #Change /dev/ttyACM0 to your com port

GMAIL_LOGIN = '***********@gmail.com'
GMAIL_PASSWORD = '************'
SEND_TO = '**********@txt.att.net'
 
def send_email(subject, message, from_addr=GMAIL_LOGIN, to_addr=SEND_TO):
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr
 
    server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(GMAIL_LOGIN,GMAIL_PASSWORD)
    server.sendmail(from_addr, to_addr, msg.as_string())
    server.close()

last_result = ""

while 1: #loop forever
   result = commands.getoutput(ser)
   if result.strip() == "1" and result.strip() != last_result:
    status=open('garage.txt', 'w')
    status.write("Garage door is open")
    send_email('OPEN', 'The garage door is open')
    status.close()
    last_result = result.strip();
#    print("open")

   elif result.strip() == "0" and result.strip() != last_result:
    status=open('garage.txt', 'w')
    status.write("Garage door is closed")
    send_email('CLOSED','The garage door is closed')
    status.close()
    last_result = result.strip();
#    print("closed")
ASKER CERTIFIED SOLUTION
Avatar of unknown_routine
unknown_routine
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dynamicOne
dynamicOne

ASKER

If I wanted to add the time and append to the file would I write it like this? I would like to add the result variable.

localtime = time.asctime( time.localtime(time.time()) )
outFile = open('sample.txt', 'a+')
outFile.write('\n' +result + ', ' + localtime)
outFile.close()
SOLUTION
Avatar of Sharon Seth
Sharon Seth
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial