1 import os
2 import shelve
3 from ConfigParser import ConfigParser
4
5 __all__=["storage_dir", "config", "db"]
6
8 """
9 Obtain a directory suitable for storing a persistent file.
10
11 Accepts an optional directory name. If C{directory} is an absolute path, it
12 will be treated as such. Otherwise, it will be treated as a path relative
13 to a writeable directory (on *nix, it's the current user's home directory.
14 On Windows, it's the roaming profile Application Data directory).
15
16 If the resulting absolute path refers to a directory that does not exist,
17 it will be created.
18 """
19 if not os.path.isabs(directory):
20 try:
21 from win32com.shell import shellcon, shell
22 except ImportError:
23 home = os.path.expanduser("~")
24 else:
25 home = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
26 directory = os.path.join(home, directory)
27 if not os.path.exists(directory):
28 os.makedirs(directory)
29 return directory
30
31
33 """
34 Wrapper that provides dictionary-like access
35 """
36 - def __init__(self, config, name, savefunc):
37 self.name = name
38 self.config = config
39 self.savefunc = savefunc
40
42 return self.config.get(self.name, key)
43
45 value = str(value)
46 if not self.config.has_section(self.name):
47 self.config.add_section(self.name)
48 self.config.set(self.name, key, value)
49 self.savefunc()
50
52 return str(dict(self.items()))
53
56
58 return self.config.options(self.name)
59
61 return [self[key] for key in self.keys()]
62
64 return option in self.keys()
65
66
96
97
98 -def config(filename, directory=""):
99 """
100 Open and parse a config file C{filename} in an optional given directory
101 C{directory}.
102
103 C{directory} will be passed through L{storage_dir}, so it may be a path
104 relative to the user's home directory. If left blank, therefore, it will be
105 the user's home directory itself.
106 """
107 directory = storage_dir(directory)
108 config = ConfigStorage(os.path.join(directory, filename))
109 return config
110
111
112 -def db(filename, directory=""):
113 """
114 Create or load a pickled dictionary from C{filename} in optional
115 C{directory}.
116
117 C{directory} will be passed through L{storage_dir}, so it may be a path
118 relative to the user's home directory.
119 """
120 directory = storage_dir(directory)
121 return shelve.open(os.path.join(directory, filename), writeback=True)
122