Akash Joshi
Akash Joshi

Reputation: 1

Put checks at multiple points in Python code to trigger an email if the code fails

I am using win32com.client to trigger an outlook email to myself from Python.I have that figured out and created a function to trigger emails which works. Now, I want to put multiple checks in my python code so that I can get email notifications if my code fails in that section.

The logical flow is Something like this:

if code between lines 1 to 50 fails:
    Send email with the message that data read failed
if code between lines 51 to 200 fails:
    Send email with the message that the algorithm failed
if code between lines 201 to 300 fails:
    Send email with the message that the write failed

Upvotes: 0

Views: 55

Answers (2)

Georgina Skibinski
Georgina Skibinski

Reputation: 13387

To extract error line number:

import sys

try:
    x!=56
except:
    lineno = sys.exc_info()[-1].tb_lineno
    print(lineno)
    if(0<=lineno<50): do_something_50()
    elif(50<=lineno<100): do_something_100()
    elif(100<=lineno<150): do_something_150()
    else: ...

Outputs:

4

Upvotes: 0

abc
abc

Reputation: 11929

You can create a function, or one for each specific task, e.g., read_data, algo, and write_output. If something goes wrong an exception will be raised. Then, you can catch the exception and send the email accordingly.

class ReadFailed(Exception):
   pass

def my_function():
   raise ReadFailed('read has failed')

try:
    my_function()
except ReadFailed:
    send_email('data_failed')
except AlgoFailed:
     send_email('algo_failed')
except WriteFailed:
     send_email('write_failed')  

Upvotes: 2

Related Questions