title: How to make a program wait for a lock on a sqlite database
body: <p>I have a program that runs as part of a larger process with the sole purpose being to safely copy a sqlite database to another folder for back-up.  Only problem is that my production run just went down because the database was locked by other processes.  Is there a way I can specify for this program to wait to obtain a lock?  It is okay if it holds up the rest of the program by a few seconds.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>import sqlite3
  import shutil
  import optparse
  import os
  import time
  import logging
  
  logging.basicConfig(level=logging.INFO, format="[%(levelname)s] - %(message)s")
  logging.disable(logging.CRITICAL)
  
  def sqlite3_backup(db_file, backup_dir):
      print 'DB is: ', db_file + '\n', 'Backup Dir is: ', backup_dir
      if not os.path.isdir(backup_dir):
          raise Exception("Backup directory does not exist: {0}".format(backup_dir))
  
      with sqlite3.connect(db_file) as conn:
          logging.info('Connected to the database.')
          cursor = conn.cursor()
          cursor.execute('begin immediate')
          shutil.copy(db_file, backup_dir)
          logging.info('Closing the database.')
  
  usage = "%prog [options] db-file backup-dir"
  description = """\
  Backup sqlite3 database to a directory, appending a datestamp on the backup."""
  
  def get_options():
      parser = optparse.OptionParser(usage=usage, description=description)
      opts, args = parser.parse_args()
      if len(args) != 2:
          raise parser.error("Incorrect number of parameters")
  
      opts.databasefile, opts.backupdir = args
      return opts
  
  if __name__ == '__main__':
      opts = get_options()
      sqlite3_backup(opts.databasefile, opts.backupdir)
  </code></pre>