Mercurial > hg > config
comparison python/optparse_undefined.py @ 193:3efe894f9d79
add a simple example for optparse_undefined
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Fri, 20 Jan 2012 14:15:16 -0800 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
192:4b9f353fc416 | 193:3efe894f9d79 |
---|---|
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' |