optparse_required.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env python
  2. # class to parse modis data
  3. #
  4. # (c) Copyright Luca Delucchi 2013
  5. # Authors: Luca Delucchi
  6. # Email: luca dot delucchi at iasma dot it
  7. #
  8. ##################################################################
  9. #
  10. # This MODIS Python class is licensed under the terms of GNU GPL 2.
  11. # This program is free software; you can redistribute it and/or
  12. # modify it under the terms of the GNU General Public License as
  13. # published by the Free Software Foundation; either version 2 of
  14. # the License, or (at your option) any later version.
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  18. # See the GNU General Public License for more details.
  19. #
  20. ##################################################################
  21. """Module to extend optparse, it add required options and new types to use
  22. into gui module.
  23. Classes:
  24. * :class:`OptionWithDefault`
  25. * :class:`OptionParser`
  26. """
  27. import optparse
  28. # classes for required options
  29. STREQUIRED = 'required'
  30. class OptionWithDefault(optparse.Option):
  31. """Extend optparse.Option add required to the attributes and some new
  32. types for the GUI
  33. """
  34. ATTRS = optparse.Option.ATTRS + [STREQUIRED]
  35. TYPES = optparse.Option.TYPES + ('file', 'output', 'directory')
  36. def __init__(self, *opts, **attrs):
  37. """Function to initialize the object"""
  38. if attrs.get(STREQUIRED, False):
  39. attrs['help'] = '(Required) ' + attrs.get('help', "")
  40. optparse.Option.__init__(self, *opts, **attrs)
  41. class OptionParser(optparse.OptionParser):
  42. """Extend optparse.OptionParser"""
  43. def __init__(self, **kwargs):
  44. """Function to initialize the object"""
  45. kwargs['option_class'] = OptionWithDefault
  46. optparse.OptionParser.__init__(self, **kwargs)
  47. def check_values(self, values, args):
  48. """Check if value is required for an option"""
  49. for option in self.option_list:
  50. if hasattr(option, STREQUIRED) and option.required:
  51. if not getattr(values, option.dest):
  52. self.error("option {opt} is required".format(opt=str(option)))
  53. return optparse.OptionParser.check_values(self, values, args)