TAGS :Viewed: 383 - Published at: a few seconds ago

[ How to execute code when a Python script is closed out? ]

I have a raspberry pi that records temperature and stores them in a MySQL database on my website. I often toy with the script, so I am hitting ctrl+c on the running script and re executing it. I would like to properly issue close() on the database connection. How can I run a line of code when the script is exited in python?

import MySQLdb
con = MySQLdb.connect(...)
cursor = con.cursor() 

# ...

#if script closes:
   #con.close()

Answer 1


import MySQLdb
con = MySQLdb.connect(...)
cursor = con.cursor() 

try:
    # do stuff with your DB    
finally:
    con.close()

The finally clause is executed on success as well as on error (exception).

If you hit Ctrl-C, you get a KeyboardInterrupt exception.

Answer 2


or:

import atexit

def close_db(con):
    con.close()
    # any other stuff you need to run on exiting

import MySQLdb
con = MySQLdb.connect(...)

# ...

atexit.register(close_db, con=con)

See here for more info.