Advertisement
gene_wood

Untitled

Jul 6th, 2011
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1. #! /usr/bin/env python
  2. __doc__ = """
  3. example of cascading options with ConfigParser and OptionParser
  4. from : http://thoughtsbyclayg.blogspot.com/2009/10/python-over-riding-options-with.html
  5. """
  6.  
  7. # imports
  8. import sys
  9. from ConfigParser import ConfigParser
  10. from optparse import OptionParser
  11. # constants
  12. default_option = 'default_value'
  13. default_toggle = True
  14.  
  15. # classes
  16. # internal functions
  17.  
  18. def main():
  19.     # create a config parser
  20.     # config parser objects store all options as strings
  21.     config = ConfigParser({'option':str(default_option),
  22.                            'toggle':str(default_toggle),
  23.                           })
  24.     config.read('example.cfg')
  25.      
  26.     # create command line option parser
  27.     parser = OptionParser("%prog [options]" + __doc__.rstrip())
  28.      
  29.     # configure command line options
  30.     parser.add_option("-o", "--option", action="store", dest="option", help="set option")
  31.     parser.add_option("-t", "--toggleOff", action="store_false", dest="toggle", help="set toggle off")
  32.     parser.add_option("-T", "--toggleOn", action="store_true", dest="toggle", help="set toggle on")
  33.      
  34.     # read config objects defaults section into a dictionary
  35.     config_options = config.defaults()
  36.     # config_options is dictionary of strings, over-ride toggle to bool
  37.     for dest in [option.dest for option in parser.option_list if option.action.lower() in ('store_true', 'store_false')]:
  38.         if config.has_option('DEFAULT', dest) and not isinstance(config_options[dest], bool):
  39.             config_options[dest] = config.getboolean('DEFAULT',dest)
  40.  
  41.     # feed dictionary of defaults into parser object
  42.     parser.set_defaults(**config_options)
  43.  
  44.     # parse command line options
  45.     (options, args) = parser.parse_args()
  46.  
  47.     print parser.values
  48.  
  49.     return 0;
  50.  
  51. if __name__ == '__main__':
  52.     status = main()
  53.     sys.exit(status)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement