2
from optparse import OptionParser
4
5
class UserError(Exception):
9
def add_dict(name, **kwargs):
11
setattr(func, name, kwargs)
17
return add_dict('_types', **kwargs)
20
return add_dict('_helps', **kwargs)
24
def get_function_parser(function):
25
parser = OptionParser()
26
args, ignore, ignored, defaults = inspect.getargspec(function)
28
arg_type = function._types.get(arg)
31
arg_help = getattr(function, '_helps', {}).get(arg)
32
if arg_help is not None:
33
arg_help +=' Default: %default.'
34
parser.add_option('--%s' % arg, type=arg_type, help=arg_help)
35
if defaults is not None:
36
defaults_dict = dict(zip(args, defaults))
37
option_defaults = dict(
38
(key, value) for key, value in defaults_dict.items()
39
if parser.defaults.get(key, '') is None)
40
parser.set_defaults(**option_defaults)
9
45
"""Base class for subcommands."""
14
def parse_args(cls, args):
50
def parse_args(cls, command, args):
16
52
raise UserError('Too many arguments.')
20
def set_defaults(cls, parser):
21
args, ignored, ignored, defaults = inspect.getargspec(cls.run)
24
defaults_dict = dict(zip(args, defaults))
25
option_defaults = dict(
26
(key, value) for key, value in defaults_dict.items()
27
if parser.defaults.get(key, '') is None)
28
parser.set_defaults(**option_defaults)
31
def run_from_args(cls, cmd_args):
32
parser = cls.get_parser()
33
cls.set_defaults(parser)
56
def run_from_args(cls, command, cmd_args):
57
parser = get_function_parser(command)
34
58
options, args = parser.parse_args(cmd_args)
35
kwargs = cls.parse_args(args)
59
kwargs = cls.parse_args(command, args)
36
60
kwargs.update(options.__dict__)
40
64
def run_subcommand(cls, argv):