dodecafonico
dodecafonico

Reputation: 305

How to Handle python script errors and sending them by email

I am relatively new to Python.

I have a Python script that grabs some information from the internet and then inserts in a database. I want to run it with cron daily and have the script send me an email each day after it is done.

I already have the email part figured out and it is working for sending the elapsed time and the total records inserted in the database, like this:

at the start of the script:

records_inserted = 0
t1_start = time.perf_counter()

and at the end of the script:

t1_stop = time.perf_counter()

msg = EmailMessage()

msg.set_content("Total elapsed time: %.1f [min]" % ((t1_stop-t1_start)/60) + 
"\n\nThe total number of records inserted in the database was: " + 
str(records_inserted))

email_from = “[email protected]"
email_to = “[email protected]"
gmail_password = “xxxxxx”

msg['From'] = email_from
msg['To'] = email_to
msg['Subject'] = “Script executed"

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email_from, gmail_password)
server.send_message(msg)

server.quit()

Now, if something in the webpages where I'm getting the content from breaks or changes or there is any error for any reason, I would like to see the errors also in that daily email.

What would be the best way to handle and store(maybe an array) in case there would be one or several errors during execution, and have the error number and description written as part of the email body so I am aware as soon as possible and can take a look and correct as necessary?

Thanks!

Upvotes: 0

Views: 1140

Answers (1)

dodecafonico
dodecafonico

Reputation: 305

The solution proposed by @fernandezcuesta in the comments is working nicely for me.

I wrappped all the code that 'does the stuff' into a try: except Exception as _ex: and attach repr(_ex) to my mail

Upvotes: 1

Related Questions