home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pytho152.zip / emx / lib / python1.5 / whichdb.py < prev    next >
Text File  |  2000-08-10  |  1KB  |  58 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.     # See if the file exists, return None if not
  29.     try:
  30.         f = open(filename, "rb")
  31.     except IOError:
  32.         return None
  33.  
  34.     # Read the first 4 bytes of the file -- the magic number
  35.     s = f.read(4)
  36.     f.close()
  37.  
  38.     # Return "" if not at least 4 bytes
  39.     if len(s) != 4:
  40.         return ""
  41.  
  42.     # Convert to 4-byte int in native byte order -- return "" if impossible
  43.     try:
  44.         (magic,) = struct.unpack("=l", s)
  45.     except struct.error:
  46.         return ""
  47.  
  48.     # Check for GNU dbm
  49.     if magic == 0x13579ace:
  50.         return "gdbm"
  51.  
  52.     # Check for BSD hash
  53.     if magic in (0x00061561, 0x61150600):
  54.         return "dbhash"
  55.  
  56.     # Unknown
  57.     return ""
  58.