4
class UserError(Exception):
8
class OptionParser(optparse.OptionParser):
10
UNSPECIFIED = object()
12
def add_option(self, *args, **kwargs):
13
"""Add an option, with the default that it not be included."""
14
kwargs['default'] = kwargs.get('default', self.UNSPECIFIED)
15
optparse.OptionParser.add_option(self, *args, **kwargs)
17
def parse_args_dict(self, cmd_args):
18
"""Return a dict of specified options.
20
Unspecified options with no explicit default are not included in the
22
options, args = self.parse_args(cmd_args)
24
item for item in options.__dict__.items()
25
if item[1] is not self.UNSPECIFIED)
26
return args, option_dict
30
"""Base class for subcommands."""
35
def parse_args(cls, args):
37
raise UserError('Too many arguments.')
41
def run_from_args(cls, cmd_args):
42
args, kwargs = cls.get_parser().parse_args_dict(cmd_args)
43
kwargs.update(cls.parse_args(args))
47
def run_subcommand(cls, argv):
49
raise UserError('Must supply a command: %s.' %
50
', '.join(cls.commands.keys()))
52
command = cls.commands[argv[0]]
54
raise UserError('%s invalid. Valid commands: %s.' %
55
(argv[0], ', '.join(cls.commands.keys())))
56
command.run_from_args(argv[1:])