/neatx/lib/cli.py

http://neatx.googlecode.com/ · Python · 85 lines · 43 code · 20 blank · 22 comment · 4 complexity · a765d914ac32ac94e9661745087d30ce MD5 · raw file

  1. #
  2. #
  3. # Copyright (C) 2009 Google Inc.
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful, but
  11. # WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. # General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  18. # 02110-1301, USA.
  19. """Module for command line interface functions"""
  20. import logging
  21. import optparse
  22. import sys
  23. from neatx import config
  24. from neatx import constants
  25. from neatx import utils
  26. class GenericProgram(object):
  27. def __init__(self, logsetup):
  28. self.logsetup = logsetup
  29. self.cfg = None
  30. self.args = None
  31. self.options = None
  32. def BuildOptions(self):
  33. debug_opt = optparse.make_option("-d", "--debug", default=False,
  34. action="store_true",
  35. help="Enable debug logging")
  36. logtostderr_opt = optparse.make_option("--logtostderr", default=False,
  37. action="store_true",
  38. help="Log to stderr")
  39. return [debug_opt, logtostderr_opt]
  40. def Main(self):
  41. self.logsetup.Init()
  42. logging.debug("Started with args %r", sys.argv)
  43. try:
  44. (self.options, self.args) = self.ParseArgs()
  45. self.cfg = config.Config(constants.CONFIG_FILE)
  46. self._ConfigLogging()
  47. self.Run()
  48. except (SystemExit, KeyboardInterrupt):
  49. raise
  50. except Exception:
  51. logging.exception("Caught exception")
  52. sys.exit(constants.EXIT_FAILURE)
  53. def ParseArgs(self):
  54. parser = optparse.OptionParser(option_list=self.BuildOptions(),
  55. formatter=optparse.TitledHelpFormatter())
  56. return parser.parse_args()
  57. def _ConfigLogging(self):
  58. """Configures the logging module.
  59. """
  60. debug = self.options.debug or self.cfg.debug
  61. logopts = utils.LoggingSetupOptions(debug, self.options.logtostderr)
  62. self.logsetup.SetOptions(logopts)
  63. def Run(self):
  64. raise NotImplementedError()