Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env python
- __doc__ = """
- example of cascading options with ConfigParser and OptionParser
- from : http://thoughtsbyclayg.blogspot.com/2009/10/python-over-riding-options-with.html
- """
- # imports
- import sys
- from ConfigParser import ConfigParser
- from optparse import OptionParser
- # constants
- default_option = 'default_value'
- default_toggle = True
- # classes
- # internal functions
- def main():
- # create a config parser
- # config parser objects store all options as strings
- config = ConfigParser({'option':str(default_option),
- 'toggle':str(default_toggle),
- })
- config.read('example.cfg')
- # create command line option parser
- parser = OptionParser("%prog [options]" + __doc__.rstrip())
- # configure command line options
- parser.add_option("-o", "--option", action="store", dest="option", help="set option")
- parser.add_option("-t", "--toggleOff", action="store_false", dest="toggle", help="set toggle off")
- parser.add_option("-T", "--toggleOn", action="store_true", dest="toggle", help="set toggle on")
- # read config objects defaults section into a dictionary
- config_options = config.defaults()
- # config_options is dictionary of strings, over-ride toggle to bool
- for dest in [option.dest for option in parser.option_list if option.action.lower() in ('store_true', 'store_false')]:
- if config.has_option('DEFAULT', dest) and not isinstance(config_options[dest], bool):
- config_options[dest] = config.getboolean('DEFAULT',dest)
- # feed dictionary of defaults into parser object
- parser.set_defaults(**config_options)
- # parse command line options
- (options, args) = parser.parse_args()
- print parser.values
- return 0;
- if __name__ == '__main__':
- status = main()
- sys.exit(status)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement