Execute a function in Python when the main application is finished running
class Report:
def __init__(self):
self.message = 'This is the first line'
report_obj = Report()
from report import report_obj
def send_email():
print('\033[0;31m')
print('Sending email...')
print('\033[m')
import sys
from report import report_obj
from email import send_email
# Register the send_email function to run when this program ends
import atexit
atexit.register(send_email)
# Print the original contents of the report_obj message
print('\nOriginal message:')
print('\033[0;34m')
print('===========================')
print(report_obj.message)
print('===========================')
print('\033[m')
# Add a line to the report_obj message
report_obj.message += '\nThis is the second line'
# Print the the new contents of the report_obj message
print('Message after adding a line:')
print('\033[0;34m')
print('===========================')
print(report_obj.message)
print('===========================')
print('\033[m')
When driver.py
finishes running, email.send_email()
is executed. This is because in the driver, it is registered in the atexit
module:
import atexit
atexit.register(send_email)
which means that when the driver is finished and is about to exit, the send_email()
function will be the last thing that runs. In this example send_email()
simply prints that it's sending an email, but this is where you should actually email report_obj
out.
See this script in action.