Mercurial > rinkhals
comparison gamelib/config.py @ 411:03d5cb669298
Add config file and command line parameters.
author | Jeremy Thurgood <firxen@gmail.com> |
---|---|
date | Sat, 21 Nov 2009 11:18:08 +0000 |
parents | |
children | 8897a436a8cb |
comparison
equal
deleted
inserted
replaced
410:e83ec14163f2 | 411:03d5cb669298 |
---|---|
1 # level.py | |
2 | |
3 from ConfigParser import RawConfigParser | |
4 from optparse import OptionParser | |
5 | |
6 class Config(object): | |
7 """Container for various global configuration knobs and levers.""" | |
8 | |
9 valid_options = { | |
10 'sound': {'type': 'boolean', 'default': 'true'}, | |
11 'level_name': {'type': 'string', 'default': 'two_weeks'}, | |
12 } | |
13 | |
14 config_filename = 'config.ini' | |
15 | |
16 def configure(self, params=None): | |
17 self._config = RawConfigParser(dict( | |
18 [(k, v['default']) for k, v in self.valid_options.items() if 'default' in v] | |
19 )) | |
20 self._config.add_section('Options') | |
21 self._set_up_params(params) | |
22 self._config.read(self.config_filename) | |
23 self._process_params() | |
24 | |
25 def _set_up_params(self, params): | |
26 parser = OptionParser() | |
27 parser.add_option("-c", "--config", metavar="FILE", dest="config_filename", | |
28 help="read configuration from FILE") | |
29 parser.add_option("-l", "--level", metavar="LEVEL", dest="level_name", | |
30 help="select level LEVEL") | |
31 parser.add_option("--sound", action="store_const", const="on", dest="sound", | |
32 help="enable sound") | |
33 parser.add_option("--no-sound", action="store_const", const="off", dest="sound", | |
34 help="disable sound") | |
35 (self._opts, _) = parser.parse_args(params or []) | |
36 self.config_filename = self._opts.config_filename or self.config_filename | |
37 | |
38 def _process_params(self): | |
39 for name in self.valid_options: | |
40 opt = getattr(self._opts, name) | |
41 if opt is not None: | |
42 self._config.set('Options', name, opt) | |
43 | |
44 def __getattr__(self, name): | |
45 if name not in self.valid_options: | |
46 raise AttributeError(name) | |
47 get_methods = { | |
48 'string': lambda n: self._config.get('Options', n), | |
49 'boolean': lambda n: self._config.getboolean('Options', n), | |
50 } | |
51 return get_methods[self.valid_options[name].get('type', 'string')](name) | |
52 | |
53 # Here's a global variable. Don't try this at home, kids! | |
54 config = Config() |