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

python

Solution

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.

Problem

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() ```

Original source