コード例 #1
0
def get_routes():
    """
    This function contains the dictionary of possible commands.
    :return: `dict` of possible commands, with the format: `name -> class`
    """

    # Dynamic load:
    # def class_filter(klass):
    #     return inspect.isclass(klass) \
    #            and klass.__module__ == BaseCommand.__module__ \
    #            and issubclass(klass, BaseCommand) \
    #            and klass is not BaseCommand
    #
    # routes = inspect.getmembers(
    #     sys.modules[BaseCommand.__module__],
    #     class_filter
    # )
    # return dict((route.label(), route) for _, route in routes)

    return {
        ListCommand.label(): ListCommand,
        DoneCommand.label(): DoneCommand,
        UndoneCommand.label(): UndoneCommand,
        NewCommand.label(): NewCommand,
        ExitCommand.label(): ExitCommand,
    }
コード例 #2
0
ファイル: main.py プロジェクト: spymobilfon/PythonHomeWork
def get_routes():
    return {
        ListCommand.label(): ListCommand,
        NewCommand.label(): NewCommand,
        DoneCommand.label(): DoneCommand,
        UndoneCommand.label(): UndoneCommand,
        ExitCommand.label(): ExitCommand,
    }
コード例 #3
0
ファイル: main1.py プロジェクト: chkalov66/homeworks
def get_routes():
    """`Эта функция содержит словарь возможных команд.
    Возвращает словарь возможных команд в формате:` name -> class`
    """
    return {
        ListCommand.label(): ListCommand,
        NewCommand.label(): NewCommand,
        DoneCommand.label(): DoneCommand,
        UndoneCommand.label(): UndoneCommand,
        ExitCommand.label(): ExitCommand,
    }
コード例 #4
0
def get_routes():
    """
    This function contains the dictionary of possible commands.
    :return: `dict` of possible commands, with the format: `name -> class`
    """

    return {
        ListCommand.label(): ListCommand,
        NewCommand.label(): NewCommand,
        DoneCommand.label(): DoneCommand,
        UndoneCommand.label(): UndoneCommand,
        ExitCommand.label(): ExitCommand,
    }
コード例 #5
0
ファイル: main.py プロジェクト: spymobilfon/PythonHomeWork
def parse_user_input():

    input_function = input

    message = 'Input your command: (%s): ' % '|'.join(
        {
            ListCommand.label(): ListCommand,
            NewCommand.label(): NewCommand,
            DoneCommand.label(): DoneCommand,
            UndoneCommand.label(): UndoneCommand,
            ExitCommand.label(): ExitCommand,
        }.keys())
    return input_function(message)
コード例 #6
0
def _create_commands_dictionary():
    def assign_canvas_fn(new_canvas):
        #pylint: disable=missing-docstring
        global canvas
        canvas = new_canvas

    return {
        'C': CreateCanvasCommand(assign_canvas_fn),
        'L': DrawLineCommand(lambda: canvas),
        'R': DrawRectangleCommand(lambda: canvas),
        'B': BucketFillCommand(lambda: canvas),
        'D': DeleteCommand(lambda: canvas),
        'U': UndoCommand(lambda: canvas),
        'Q': ExitCommand()
    }
コード例 #7
0
ファイル: main.py プロジェクト: ZenKaban/frii-python
def parse_user_input():
    """
    Gets the user input.
    :return: `str` with the user input.
    """

    input_function = input

    message = 'Input your command: (%s): ' % '|'.join(
        {
            ListCommand.label(): ListCommand,
            NewCommand.label(): NewCommand,
            ExitCommand.label(): ExitCommand,
        }.keys())
    return input_function(message)
コード例 #8
0
ファイル: main1.py プロジェクト: chkalov66/homeworks
def parse_user_input():
    """
    Получает пользовательский ввод.
    Возвращает: строку с пользовательским вводом.
    """
    input_function = input

    message = 'Input your command: (%s): ' % '|'.join(
        {
            ListCommand.label(): ListCommand,
            NewCommand.label(): NewCommand,
            DoneCommand.label(): DoneCommand,
            UndoneCommand.label(): UndoneCommand,
            ExitCommand.label(): ExitCommand,
        }.keys())
    return input_function(message)
コード例 #9
0
def get_routes():
    # Dynamic load
    # def class_filter(klass):
    #     return inspect.isclass(klass) \
    #            and klass.__module__ == BaseCommand.__module__ \
    #            and issubclass(klass, BaseCommand) \
    #            and klass is not BaseCommand

    # routes = inspect.getmembers(
    #     sys.modules[BaseCommand.__module__],
    #     class_filter
    # )
    # return dict((route.label(), route) for _, route in routes)

    from commands import ListCommand, NewCommand, ExitCommand
    return {
        ListCommand.label(): ListCommand,
        NewCommand.label(): NewCommand,
        ExitCommand.label(): ExitCommand,
        # DoneCommand.label(): DoneCommand,
    }
コード例 #10
0
class MainLoop(object):
    builtin_commands = {
        'exit': ExitCommand(),
        'setenv': SetenvCommand(),
        'printenv': PrintenvCommand(),
        'saveenv': SaveenvCommand(),
        'shell': ShellCommand(),
        'eval': EvalCommand(),
        'shutdown': ShutdownCommand(),
        'reboot': RebootCommand(),
        'help': HelpCommand(),
        'top': TopCommand(),
        'showips': ShowIpsCommand(),
        'showurls': ShowUrlsCommand(),
        'source': SourceCommand(),
        'less': LessCommand(),
        'clear': ClearCommand(),
        'history': HistoryCommand(),
        'echo': EchoCommand(),
        'search': SearchPipeCommand(),
        'exclude': ExcludePipeCommand(),
        'sort': SortPipeCommand(),
        'limit': LimitPipeCommand(),
        'select': SelectPipeCommand()
    }

    def __init__(self, context):
        self.context = context
        self.root_path = [self.context.root_ns]
        self.path = self.root_path[:]
        self.prev_path = self.path[:]
        self.start_from_root = False
        self.namespaces = []
        self.connection = None

    def __get_prompt(self):
        variables = {
            'path': '/'.join([x.get_name() for x in self.path]),
            'host': self.context.hostname
        }
        return self.context.variables.get('prompt').format(**variables)

    def greet(self):
        output_msg(
            _("Welcome to FreeNAS CLI! Type '?' for help at any point."))
        output_msg("")

    def cd(self, ns):
        if not self.cwd.on_leave():
            return

        self.path.append(ns)
        self.cwd.on_enter()

    def cd_up(self):
        if not self.cwd.on_leave():
            return

        del self.path[-1]
        self.cwd.on_enter()

    @property
    def cwd(self):
        return self.path[-1]

    def repl(self):
        readline.parse_and_bind('tab: complete')
        readline.set_completer(self.complete)

        self.greet()
        a = ShowUrlsCommand()
        a.run(self.context, None, None, None)

        while True:
            try:
                line = raw_input(self.__get_prompt()).strip()
            except EOFError:
                print
                return
            except KeyboardInterrupt:
                print
                continue

            self.process(line)

    def find_in_scope(self, token):
        if token in self.builtin_commands.keys():
            return self.builtin_commands[token]

        for ns in self.cwd.namespaces():
            if token == ns.get_name():
                return ns

        for name, cmd in self.cwd.commands().items():
            if token == name:
                return cmd

        return None

    def convert_literals(self, tokens):
        for i in tokens:
            if isinstance(i, Symbol):
                # Convert symbol to string
                yield i.name

            if isinstance(i, Literal):
                yield i.value

            if isinstance(i, BinaryExpr):
                if isinstance(i.right, Literal):
                    yield (i.left, i.op, i.right.value)

                if isinstance(i.right, Symbol):
                    # Convert symbol to string
                    yield (i.left, i.op, i.right.name)

                if isinstance(i.right, CommandExpansion):
                    yield (i.left, i.op, self.eval(i.right.expr))

    def format_output(self, object):
        if isinstance(object, Object):
            output_object(object)

        if isinstance(object, Table):
            output_table(object)

        if isinstance(object, (basestring, int, long, bool)):
            output_msg(object)

    def eval(self, tokens):
        oldpath = self.path[:]
        if self.start_from_root:
            self.path = self.root_path[:]
            self.start_from_root = False
        command = None
        pipe_stack = []
        args = []

        while tokens:
            token = tokens.pop(0)

            if isinstance(token, Symbol):
                item = self.find_in_scope(token.name)

                if command:
                    args.append(token)
                    continue

                if isinstance(item, Namespace):
                    self.cd(item)
                    continue

                if isinstance(item, Command):
                    command = item
                    continue

                try:
                    raise SyntaxError(
                        "Command or namespace {0} not found".format(
                            token.name))
                finally:
                    self.path = oldpath

            if isinstance(token, CommandExpansion):
                if not command:
                    try:
                        raise SyntaxError(
                            "Command expansion cannot replace command or namespace name"
                        )
                    finally:
                        self.path = oldpath

                result = self.eval(token.expr)
                if not isinstance(result, basestring):
                    try:
                        raise SyntaxError(
                            "Can only use command expansion with commands returning single value"
                        )
                    finally:
                        self.path = oldpath

                args.append(Literal(result, type(result)))
                continue

            if isinstance(token, (Literal, BinaryExpr)):
                args.append(token)
                continue

            if isinstance(token, PipeExpr):
                pipe_stack.append(token.right)
                tokens += token.left

        args = list(self.convert_literals(args))
        args, kwargs, opargs = sort_args(args)
        filter_ops = []
        filter_params = {}

        if not command:
            if len(args) > 0:
                raise SyntaxError('No command specified')

            return

        tmpath = self.path[:]

        if isinstance(command, FilteringCommand):
            for p in pipe_stack[:]:
                pipe_cmd = self.find_in_scope(p[0].name)
                if not pipe_cmd:
                    try:
                        raise SyntaxError("Pipe command {0} not found".format(
                            p[0].name))
                    finally:
                        self.path = oldpath

                pipe_args = self.convert_literals(p[1:])
                try:
                    ret = pipe_cmd.serialize_filter(self.context,
                                                    *sort_args(pipe_args))

                    if 'filter' in ret:
                        filter_ops += ret['filter']

                    if 'params' in ret:
                        filter_params.update(ret['params'])

                except NotImplementedError:
                    continue

                # If serializing filter succeeded, remove it from pipe stack
                pipe_stack.remove(p)

            ret = command.run(self.context,
                              args,
                              kwargs,
                              opargs,
                              filtering={
                                  'filter': filter_ops,
                                  'params': filter_params
                              })
        else:
            self.path = oldpath
            ret = command.run(self.context, args, kwargs, opargs)

        for i in pipe_stack:
            pipe_cmd = self.find_in_scope(i[0].name)
            pipe_args = self.convert_literals(i[1:])
            try:
                ret = pipe_cmd.run(self.context,
                                   *sort_args(pipe_args),
                                   input=ret)
            except CommandException:
                raise
            except Exception as e:
                raise CommandException(
                    _('Unexpected Error: {0}'.format(str(e))))
            finally:
                self.path = oldpath

        if self.path != tmpath:
            # Command must have modified the path
            return ret

        self.path = oldpath
        return ret

    def process(self, line):
        if len(line) == 0:
            return

        if line[0] == '!':
            self.builtin_commands['shell'].run(self.context, [line[1:]], {},
                                               {})
            return

        if line[0] == '/':
            if line.strip() == '/':
                self.prev_path = self.path[:]
                self.path = self.root_path[:]
                return
            else:
                self.start_from_root = True
                line = line[1:]

        if line == '..':
            if len(self.path) > 1:
                self.prev_path = self.path[:]
                self.cd_up()
                return

        if line == '-':
            prev = self.prev_path[:]
            self.prev_path = self.path[:]
            self.path = prev
            return

        try:
            i = parse(line)
            self.format_output(self.eval(i))
        except SyntaxError, e:
            output_msg(_('Syntax error: {0}'.format(str(e))))
        except CommandException, e:
            output_msg(_('Error: {0}'.format(str(e))))
            if self.context.variables.get('debug'):
                output_msg(e.stacktrace)
コード例 #11
0
def test_exit_command_execute():
    command = ExitCommand()
    with pytest.raises(SystemExit):
        command.execute()