home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / WHICHDB.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  2.0 KB  |  82 lines

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