opt.py 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Copyright(c) 2007. BitTorrent, Inc. All rights reserved.
  2. # author: David Harrison
  3. from ConfigParser import RawConfigParser
  4. from optparse import OptionParser
  5. from BTL.translation import _
  6. class ConfigOptionParser(RawConfigParser, OptionParser):
  7. def __init__(self, usage, default_section, config_file = None):
  8. """This is an option parser that reads defaults from a config file.
  9. It also allows specification of types for each option (unlike our mess
  10. that is mainline BitTorrent), and is only a slight extension on the
  11. classes provided in the Python standard libraries (unlike the
  12. wheel reinvention in mainline).
  13. @param usage: usage string for this application.
  14. @param default_section: section in the config file containing configuration
  15. for this service. This is a default that can be overriden for
  16. individual options by passing section as a kwarg to add_option.
  17. """
  18. self._default_section = default_section
  19. OptionParser.__init__(self,usage)
  20. RawConfigParser.__init__(self)
  21. if config_file:
  22. self.read(config_file)
  23. def add_option(self, *args,**kwargs):
  24. if 'section' in kwargs:
  25. section = kwargs['section']
  26. del kwargs['section']
  27. else:
  28. section = self._default_section
  29. if "dest" in kwargs:
  30. if not self.has_option(section, kwargs["dest"]):
  31. if not kwargs.has_key("default"):
  32. raise Exception(
  33. _("Your .conf file is invalid. It does not specify "
  34. "a value for %s.\n %s:\t%s\n") %
  35. (kwargs["dest"],kwargs["dest"],kwargs["help"]))
  36. else:
  37. if not kwargs.has_key("value_type"):
  38. kwargs["default"]=self.get(section, kwargs["dest"])
  39. else:
  40. if kwargs["value_type"] == "float":
  41. kwargs["default"] = float(self.get(section, kwargs["dest"] ))
  42. elif kwargs["value_type"] == "int":
  43. kwargs["default"] = int(self.get(section, kwargs["dest"] ))
  44. elif kwargs["value_type"] == "bool":
  45. v = self.get(section, kwargs["dest"])
  46. if v == "True":
  47. kwargs["default"] = True
  48. elif v == "False":
  49. kwargs["default"] = False
  50. else:
  51. raise Exception( "Boolean value must be either 'True' or 'False'.")
  52. elif kwargs["value_type"] == "str":
  53. # canonicalize strings.
  54. v = self.get(section, kwargs["dest"])
  55. v = v.strip('"').strip()
  56. kwargs["default"] = v
  57. elif kwargs["value_type"] == "list":
  58. v = self.get(section, kwargs["dest"])
  59. kwargs["default"] = v.split(",")
  60. else:
  61. raise Exception( "Option has unrecognized type: %s" % kwargs["value_type"] )
  62. if kwargs.has_key("value_type"):
  63. del kwargs["value_type"]
  64. OptionParser.add_option(self,*args,**kwargs)