home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_Lib_whichdb.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  2.1 KB  |  89 lines

  1. """Guess which db package to use to open a db file."""
  2.  
  3. import os
  4.  
  5. if os.sep==".":
  6.     endsep = "/"
  7. else:
  8.     endsep = "."
  9.  
  10. def whichdb(filename):
  11.     """Guess which db package to use to open a db file.
  12.  
  13.     Return values:
  14.  
  15.     - None if the database file can't be read;
  16.     - empty string if the file can be read but can't be recognized
  17.     - the module name (e.g. "dbm" or "gdbm") if recognized.
  18.  
  19.     Importing the given module may still fail, and opening the
  20.     database using that module may still fail.
  21.     """
  22.  
  23.     import struct
  24.  
  25.     # Check for dbm first -- this has a .pag and a .dir file
  26.     try:
  27.         f = open(filename + endsep + "pag", "rb")
  28.         f.close()
  29.         f = open(filename + endsep + "dir", "rb")
  30.         f.close()
  31.         return "dbm"
  32.     except IOError:
  33.         pass
  34.  
  35.     # Check for dumbdbm next -- this has a .dir and and a .dat file
  36.     try:
  37.         f = open(filename + endsep + "dat", "rb")
  38.         f.close()
  39.         f = open(filename + endsep + "dir", "rb")
  40.         try:
  41.             if f.read(1) in ["'", '"']:
  42.                 return "dumbdbm"
  43.         finally:
  44.             f.close()
  45.     except IOError:
  46.         pass
  47.  
  48.     # See if the file exists, return None if not
  49.     try:
  50.         f = open(filename, "rb")
  51.     except IOError:
  52.         return None
  53.  
  54.     # Read the start of the file -- the magic number
  55.     s16 = f.read(16)
  56.     f.close()
  57.     s = s16[0:4]
  58.  
  59.     # Return "" if not at least 4 bytes
  60.     if len(s) != 4:
  61.         return ""
  62.  
  63.     # Convert to 4-byte int in native byte order -- return "" if impossible
  64.     try:
  65.         (magic,) = struct.unpack("=l", s)
  66.     except struct.error:
  67.         return ""
  68.  
  69.     # Check for GNU dbm
  70.     if magic == 0x13579ace:
  71.         return "gdbm"
  72.  
  73.     # Check for BSD hash
  74.     if magic in (0x00061561, 0x61150600):
  75.         return "dbhash"
  76.  
  77.     # BSD hash v2 has a 12-byte NULL pad in front of the file type
  78.     try:
  79.         (magic,) = struct.unpack("=l", s16[-4:])
  80.     except struct.error:
  81.         return ""
  82.  
  83.     # Check for BSD hash
  84.     if magic in (0x00061561, 0x61150600):
  85.         return "dbhash"
  86.  
  87.     # Unknown
  88.     return ""
  89.