Home > python > Dead Man’s Last Wish: the atexit module

Dead Man’s Last Wish: the atexit module

The atexit module defines a single function to register cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination.

Example
I tried today SQLite and I noticed that commit() must be called explicitly, it’s not called automatically when the program terminates. I thought that when the connection object goes out of scope, it calls commit and close, but no…

So here is my solution (extract):

SQLITE_DB = None
conn = None

def init(sqlite_db):
    """Initialize the DB."""
    global SQLITE_DB, conn
    atexit.register(commit_and_close)    # HERE
    SQLITE_DB = sqlite_db
    
    if not os.path.exists(SQLITE_DB):
        create_db()
    if not conn:
        conn = sqlite3.connect(SQLITE_DB)

def commit_and_close():
    """Commit and close DB connection."""
    if conn:
        conn.commit()
        conn.close()

You can find the full source code here.

About these ads
Categories: python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 75 other followers

%d bloggers like this: