comparison example/optparse_undefined.py @ 138:cae2a1e1b9da

from config
author Jeff Hammel <k0scist@gmail.com>
date Tue, 04 Nov 2014 15:15:25 -0800
parents
children
comparison
equal deleted inserted replaced
137:bbe1d192a61c 138:cae2a1e1b9da
1 #!/usr/bin/env python
2
3 """
4 illustrates usage of the undefined pattern from e.g.
5 http://k0s.org/mozilla/hg/bzconsole/file/tip/bzconsole/command.py
6
7 This is useful for scenarios similar to:
8 - you have base configuration in a file
9 - you have an OptionParser to read options in the command line
10 - the CLI options should overwrite the file configuration iff
11 the user specifies an option
12 """
13
14 from optparse import OptionParser
15
16 class Undefined(object):
17 def __init__(self, default):
18 self.default=default
19
20 class UndefinedOptionParser(OptionParser):
21
22 def add_option(self, *args, **kwargs):
23 kwargs['default'] = Undefined(kwargs.get('default'))
24 OptionParser.add_option(self, *args, **kwargs)
25
26 def parse_args(self, *args, **kwargs):
27 options, args = OptionParser.parse_args(self, *args, **kwargs)
28 return options, args
29
30 if __name__ == '__main__':
31
32 myparser = UndefinedOptionParser()
33 myparser.add_option("--foo", dest='foo', default='hello')
34 myparser.add_option("--bar", dest='bar', default='goodbye')
35 myparser.add_option("--baz", dest='baz', default='helloagain')
36 myparser.add_option("--fleem", dest='fleem', default='aufwiedersehen')
37
38 myconfiguration = {'foo': 'hi',
39 'bar': 'ciao'}
40 options, args = myparser.parse_args(['--foo', 'hello', '--baz', 'hola'])
41 for key, value in options.__dict__.items():
42 # XXX ideally you would move this to parse_args
43 if isinstance(value, Undefined):
44 options.__dict__[key] = myconfiguration.get(key, value.default)
45
46 assert options.foo == 'hello'
47 assert options.bar == 'ciao'
48 assert options.baz == 'hola'
49 assert options.fleem == 'aufwiedersehen'