PageRenderTime 59ms CodeModel.GetById 54ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/neatx/lib/cli.py

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