Skip to content

Instantly share code, notes, and snippets.

@mikecharles
Last active December 11, 2015 15:40
Show Gist options
  • Save mikecharles/2202966f986042045cd3 to your computer and use it in GitHub Desktop.
Save mikecharles/2202966f986042045cd3 to your computer and use it in GitHub Desktop.
Execute a function in Python when the main application is finished running

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.

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')
from report import report_obj
def send_email():
print('\033[0;31m')
print('Sending email...')
print('\033[m')
class Report:
def __init__(self):
self.message = 'This is the first line'
report_obj = Report()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment