Python @ DjangoSpin

Python: Call functions upon termination of program

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Call functions upon termination of program in Python

Call functions upon termination of program in Python

The builtin module atexit helps to call functions upon normal termination of Python scripts. This is achieved using its register() function.

# Contents of testAtExit.py
import atexit

def bye():
    print("Goodbye...")

atexit.register(bye)

# Command prompt / Terminal
$ python path_to_testAtExit.py
Goodbye...

Python allows to register more than one functions, and to pass arguments to these functions.

# Contents of testAtExit.py
import atexit

def bye(name):
    print("Goodbye {}...".format(name))

atexit.register(bye, 'Ethan')

# Command prompt / Terminal
$ python path_to_testAtExit.py
Goodbye Ethan...

Note that registered functions are not called in the following events:

  1. When program is exited using os._exit(). The registered functions are called when the program is exited using sys.exit().
  2. When the program is killed with a signal. This can be done using the subprocess module and kill() function of the os module.

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply