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")
dynamicOneAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

unknown_routineCommented:
Put this wherever you want to do logging:

f = open('myfile','w')
f.write('This is a test!\n')
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dynamicOneAuthor Commented:
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()
0
Sharon SethCommented:
yes , that's how you write it
0
clockwatcherCommented:
Rather than roll your own, you may want to use python's logging module -- http://docs.python.org/2/howto/logging.html.  If you do much python programming, it'll come up quite a bit so it's a good module to be familiar with..  It supports different log levels.  You can direct the output to various sources (email, files, syslogs).  You can create module specific loggers.  It supports different output formats (including things like timestamping -- shown in the example below).  All in all, it's pretty darn useful:

import logging
logging.basicConfig(filename='logfile.log',
                               format='%(asctime)s %(message)s', 
                               level=logging.INFO)
logging.info('this is general information')
logging.debug('this is debugging information.  Depending on the log level you're running at, you may not see it")

Open in new window



#! /usr/bin/env python

import logging
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' 

logging.basicConfig(filename='garage.log',format='%(asctime)s %(message)s', level=logging.INFO)
 
def send_email(subject, message, from_addr=GMAIL_LOGIN, to_addr=SEND_TO):
    logging.debug('entering send_mail')  # example of a different logging level
    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();
    logging.info('door 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();
    logging.info('door closed')

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.