Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
whichdb Namespace Reference

Functions

def whichdb
 

Detailed Description

Guess which db package to use to open a db file.

Function Documentation

def whichdb.whichdb (   filename)
Guess which db package to use to open a db file.

Return values:

- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" or "gdbm") if recognized.

Importing the given module may still fail, and opening the
database using that module may still fail.

Definition at line 5 of file whichdb.py.

References aifc.open().

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