예제 #1
0
파일: command.py 프로젝트: ot/bpt
class Command(object):
    '''Base class for Command objects.'''
    
    def __init__(self, options=None):
        if options is None:
            options = []
        self.options = options

    # Override the following 
    # __doc__ = ...
    usage_args = '[ options ... ]'

    @classproperty
    def name(cls):
        return cls.__name__
    
    @classproperty
    def description(cls):
        return re.sub('\s+', ' ', cls.__doc__)

    def execute(self, config, cmd_args):
        options, pos_args = self._parse_args(cmd_args)
        try:
            return self._run(config, options, pos_args)
        except InvalidCommandLine:
            self.parser.print_help()
            return 1

    def _parse_args(self, args):
        self.parser = BPTOptionParser(
            usage='%%prog %s %s' % (self.name, self.usage_args),
            description=self.description)
        self.parser.add_options(self.options)
        return self.parser.parse_args(args)

    def _require_args(self, cmd_args, at_least=0, at_most=None):
        l = len(cmd_args)
        if l < at_least:
            raise InvalidCommandLine
        if at_most is not None and l > at_most:
            raise InvalidCommandLine
        

    def _run(self, config, options, pos_args):
        raise NotImplementedError
예제 #2
0
class Command(object):
    '''Base class for Command objects.'''
    def __init__(self, options=None):
        if options is None:
            options = []
        self.options = options

    # Override the following
    # __doc__ = ...
    usage_args = '[ options ... ]'

    @classproperty
    def name(cls):
        return cls.__name__

    @classproperty
    def description(cls):
        return re.sub('\s+', ' ', cls.__doc__)

    def execute(self, config, cmd_args):
        options, pos_args = self._parse_args(cmd_args)
        try:
            return self._run(config, options, pos_args)
        except InvalidCommandLine:
            self.parser.print_help()
            return 1

    def _parse_args(self, args):
        self.parser = BPTOptionParser(usage='%%prog %s %s' %
                                      (self.name, self.usage_args),
                                      description=self.description)
        self.parser.add_options(self.options)
        return self.parser.parse_args(args)

    def _require_args(self, cmd_args, at_least=0, at_most=None):
        l = len(cmd_args)
        if l < at_least:
            raise InvalidCommandLine
        if at_most is not None and l > at_most:
            raise InvalidCommandLine

    def _run(self, config, options, pos_args):
        raise NotImplementedError