Python prompt_toolkit.history 模块,InMemoryHistory() 实例源码

我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用prompt_toolkit.history.InMemoryHistory()

项目:azure-cli-shell    作者:Azure    | 项目源码 | 文件源码
def __init__(self, completer=None, styles=None,
                 lexer=None, history=InMemoryHistory(),
                 app=None, input_custom=sys.stdout, output_custom=None):
        self.styles = styles
        if styles:
            self.lexer = lexer or AzLexer
        else:
            self.lexer = None
        self.app = app
        self.completer = completer
        self.history = history
        self._cli = None
        self.refresh_cli = False
        self.layout = None
        self.description_docs = u''
        self.param_docs = u''
        self.example_docs = u''
        self._env = os.environ
        self.last = None
        self.last_exit = 0
        self.input = input_custom
        self.output = output_custom
        self.config_default = ""
        self.default_command = ""
项目:os-shell    作者:bdastur    | 项目源码 | 文件源码
def __init__(self):
        history = InMemoryHistory()
        os_commandhelper = OSCommandHelper()
        resource = Resource()
        os_completer = OSCompleter(os_commandhelper, resource)

        self.main_buffer = Buffer(
            accept_action=AcceptAction.RETURN_DOCUMENT,
            history=history,
            auto_suggest=AutoSuggestFromHistory(),
            completer=os_completer,
            complete_while_typing=True)

        self.help_buffer = Buffer(
            is_multiline=True)
        self.help_buffer.text = "HELP"

        os_completer.help_buffer = self.help_buffer

        self.buffers = {
            DEFAULT_BUFFER: self.main_buffer,
            'HELP': self.help_buffer
        }
项目:Liljimbo-Chatbot    作者:chrisjim316    | 项目源码 | 文件源码
def interactive(self, context=None):
        """Runs interactive command line chat between user and bot. Runs
        indefinitely until EOF is entered to the prompt.

        context -- optional initial context. Set to {} if omitted
        """
        if context is None:
            context = {}

        # input/raw_input are not interchangeable between Python 2 and 3
        try:
            input_function = raw_input
        except NameError:
            input_function = input

        history = InMemoryHistory()
        while True:
            try:
                message = prompt(INTERACTIVE_PROMPT, history=history, mouse_support=True).rstrip()
            except (KeyboardInterrupt, EOFError):
                return
            print(self.message(message, context))
项目:cdbcli    作者:kevinjqiu    | 项目源码 | 文件源码
def _run(self):
        args = {
            'history': history.InMemoryHistory(),
            'enable_history_search': True,
            'enable_open_in_editor': True,
            'lexer': lexer,
            'completer': get_completer(self._environment, self._couch_server),
            'style': style,
        }
        while True:
            try:
                cli = pt.CommandLineInterface(application=shortcuts.create_prompt_application(self.prompt, **args),
                                              eventloop=shortcuts.create_eventloop())
                self._environment.cli = cli
                cmd_text = cli.run().text.rstrip()
                eval_(self._environment, self._couch_server, cmd_text)
                cli.reset()
            except RuntimeError as e:
                self._environment.output(str(e))
            except (EOFError, KeyboardInterrupt):
                self._environment.output('Exiting...')
                break
项目:scm    作者:rookiebulls    | 项目源码 | 文件源码
def login(url, username, password, update_apidoc, display_meta):
    s = requests.Session()
    r = s.post('{}/api/rest/auth/login'.format(url),
               json={'username': username, 'password': password})
    rest = r.json()
    if rest['status'] == 'login.failed':
        click.secho('Fail to login, wrong username or password!', fg='red')
        return
    headers = {item: rest[item]
               for item in ('token', 'apiToken', 'apiLicenseToken')}
    s.headers = headers

    if update_apidoc:
        update_completions(s, url)

    click.echo('Syntax: <command> [params] [options]')
    click.echo('Press `Ctrl+D` to exit')
    history = InMemoryHistory()
    history.append('scm apiname')
    history.append('help apiname')
    while True:
        try:
            text = prompt(get_prompt_tokens=get_prompt_tokens,
                          completer=SCMCompleter(TextUtils(display_meta)),
                          auto_suggest=AutoSuggestFromHistory(),
                          style=DocumentStyle,
                          history=history,
                          on_abort=AbortAction.RETRY)
        except EOFError:
            break
        process_command(s, url, text)
项目:bptc_wallet    作者:ceddie    | 项目源码 | 文件源码
def __init__(self, title='Interactive Shell', add_help=True):
        self.title = title
        self.style = style_from_dict({
            Token.Toolbar: '#ffffff bg:#333333',
        })
        if add_help:
            self.commands['help'] = dict(
                help = 'Show this help message',
            )
        self.history = InMemoryHistory()
        self.completer = WordCompleter(sorted(self.commands.keys()))
        self.parser = self._create_parser()
        self.registry = self._create_keybindings_registry()
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
        self.init_prompt_toolkit_cli()
        self.init_term_title()
        self.keep_running = True

        self.debugger_history = InMemoryHistory()
项目:litchi    作者:245967906    | 项目源码 | 文件源码
def __init__(self):
        self._user = User.objects.get(username=getpass.getuser())
        self._inventory = self._user.get_inventory_info()
        self._history = InMemoryHistory()
        self._completer = WordCompleter(
            words=['help', 'show', 'attach', 'exit'],
            ignore_case=True,
            sentence=True,
            match_middle=True,
        )
项目:azure-shell    作者:yokawasa    | 项目源码 | 文件源码
def __init__(self, config, completer):
        self._cli = None
        self._env = os.environ.copy()
        self.history = InMemoryHistory()
        self.file_history = FileHistory(
                "{}/history".format(AzureShellCache.Instance().get('base_dir')))
        self._config = config
        self.completer = completer
项目:we-get    作者:rachmadaniHaryono    | 项目源码 | 文件源码
def shell(self, items, pargs):
        self.pargs = pargs
        self.items = items
        stdout.write(
            '\n')  # When the fetching messege ends need to add \n after \r.
        self.prompt_show_items()
        history = InMemoryHistory()

        while True:
            p = prompt(
                u'we-get > ', history=history,
                auto_suggest=AutoSuggestFromHistory(),
                completer=WGCompleter(list(self.items.keys())),
                style=we_get_prompt_style
            )

            if self.prompt_no_command(p):
                continue
            elif self.prompt_is_single_command(p):
                command = p
                args = None
            else:
                _ = p.split()
                command = _[0]
                _.pop(0)
                args = ' '.join(_)
            if not self.prompt_verify_command(command, args):
                continue
            elif not self.prompt_parse_command(command, args):
                break
项目:azure-cli    作者:Azure    | 项目源码 | 文件源码
def __init__(self, completer=None, styles=None,
                 lexer=None, history=InMemoryHistory(),
                 app=None, input_custom=sys.stdin, output_custom=None,
                 user_feedback=False, intermediate_sleep=.25, final_sleep=4):
        self.styles = styles
        if styles:
            self.lexer = lexer or AzLexer
        else:
            self.lexer = None
        self.app = app
        self.completer = completer
        self.history = history
        self._cli = None
        self.refresh_cli = False
        self.layout = None
        self.description_docs = u''
        self.param_docs = u''
        self.example_docs = u''
        self._env = os.environ
        self.last = None
        self.last_exit = 0
        self.user_feedback = user_feedback
        self.input = input_custom
        self.output = output_custom
        self.config_default = ""
        self.default_command = ""
        self.threads = []
        self.curr_thread = None
        self.spin_val = -1
        self.intermediate_sleep = intermediate_sleep
        self.final_sleep = final_sleep
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
        self.init_prompt_toolkit_cli()
        self.init_term_title()
        self.keep_running = True

        self.debugger_history = InMemoryHistory()
项目:discogs-cli    作者:jesseward    | 项目源码 | 文件源码
def cli():
    history = InMemoryHistory()
    style = style_from_pygments(get_style_by_name('monokai'))
    lexer = PygmentsLexer(DiscogsCliLexer)
    completer = Completer(fuzzy_match=False, text_utils=TextUtils())

    SYNTAX = 'Syntax: ogs <command> [options]'

    click.secho('     _ _                                    _ _ ',
                fg='yellow')
    click.secho('  __| (_)___  ___ ___   __ _ ___        ___| (_)',
                fg='yellow')
    click.secho(' / _` | / __|/ __/ _ \ / _` / __|_____ / __| | |',
                fg='yellow')
    click.secho('| (_| | \__ \ (_| (_) | (_| \__ \_____| (__| | |',
                fg='yellow')
    click.secho(' \__,_|_|___/\___\___/ \__, |___/      \___|_|_|',
                fg='yellow')
    click.secho('                       |___/', fg='yellow')

    click.echo('Version:' + __version__)
    click.echo(SYNTAX)

    while True:

        try:
            text = prompt('discogs-cli >>> ', style=style, history=history,
                          lexer=lexer, completer=completer,
                          complete_while_typing=Always())
        except EOFError:
            break

        if text in EXIT:
            break

        if text.startswith(TOKEN):
            execute(text)
        else:
            click.secho('Guru meditation error. ' + SYNTAX, fg='red')
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
        self.init_prompt_toolkit_cli()
        self.init_term_title()
        self.keep_running = True

        self.debugger_history = InMemoryHistory()
项目:uhu    作者:updatehub    | 项目源码 | 文件源码
def __init__(self, package_fn=None):
        """Creates a new interactive prompt.

        The interactive prompt will work using an exisiting
        configuration file (if it exists).

        It is also able to load an existing configuration file placed
        in a non standard place if REPL is created using the
        `package_fn`.

        Finally, if there is no configuration file present in the
        working directory, neighter a package file is explicty passed,
        `UHURepl` will create a new one.

        :param package_fn: An UHU package filename.
        """
        self.local_config = get_local_config_file()

        if package_fn is not None:
            self.package = self.load_package(package_fn)
        elif os.path.exists(self.local_config):
            self.package = self.load_package(self.local_config)
        else:
            self.package = Package()

        if self.package.product:
            self.prompt = set_product_prompt(self.package.product)
        else:
            self.prompt = 'uhu> '

        self.arg = None
        self.history = InMemoryHistory()
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
        self.init_prompt_toolkit_cli()
        self.init_term_title()
        self.keep_running = True

        self.debugger_history = InMemoryHistory()
项目:webfriend    作者:ghetzel    | 项目源码 | 文件源码
def __init__(self, browser, environment=None):
        self.browser = browser

        if environment:
            self.environment = environment
        else:
            self.environment = Environment(Scope(), browser=self.browser)

        self.completer = FriendscriptCompleter(
            sorted(self.environment.get_command_names())
        )
        self.history = InMemoryHistory()
        self.last_result = None
        self.echo_results = True
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def init_prompt_toolkit_cli(self):
        if self.simple_prompt:
            # Fall back to plain non-interactive output for tests.
            # This is very limited, and only accepts a single line.
            def prompt():
                isp = self.input_splitter
                prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
                prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
                while isp.push_accepts_more():
                    line = cast_unicode_py2(input(prompt_text))
                    isp.push(line)
                    prompt_text = prompt_continuation
                return isp.source_reset()
            self.prompt_for_code = prompt
            return

        # Set up keyboard shortcuts
        kbmanager = KeyBindingManager.for_prompt(
            enable_open_in_editor=self.extra_open_editor_shortcuts,
        )
        register_ipython_shortcuts(kbmanager.registry, self)

        # Pre-populate history from IPython's history database
        history = InMemoryHistory()
        last_cell = u""
        for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
                                                        include_latest=True):
            # Ignore blank lines and consecutive duplicates
            cell = cell.rstrip()
            if cell and (cell != last_cell):
                history.append(cell)
                last_cell = cell

        self._style = self._make_style_from_name_or_cls(self.highlighting_style)
        self.style = DynamicStyle(lambda: self._style)

        editing_mode = getattr(EditingMode, self.editing_mode.upper())

        def patch_stdout(**kwargs):
            return self.pt_cli.patch_stdout_context(**kwargs)

        self._pt_app = create_prompt_application(
                            editing_mode=editing_mode,
                            key_bindings_registry=kbmanager.registry,
                            history=history,
                            completer=IPythonPTCompleter(shell=self,
                                                    patch_stdout=patch_stdout),
                            enable_history_search=True,
                            style=self.style,
                            mouse_support=self.mouse_support,
                            **self._layout_options()
        )
        self._eventloop = create_eventloop(self.inputhook)
        self.pt_cli = CommandLineInterface(
            self._pt_app, eventloop=self._eventloop,
            output=create_output(true_color=self.true_color))
项目:style_transfer    作者:crowsonkb    | 项目源码 | 文件源码
def run(self):
        style = style_from_dict({
            Token.Prompt: 'bold',
            Token.Toolbar: '#ccc bg:#333',
            Token.Name: '#fff bold bg:#333',
        })

        history = InMemoryHistory()
        eventloop = create_eventloop()
        app = create_prompt_application(history=history, style=style,
                                        get_bottom_toolbar_tokens=self.get_bottom_toolbar_tokens,
                                        get_prompt_tokens=self.get_prompt_tokens)
        self.cli = CommandLineInterface(app, eventloop)

        with self.cli.patch_stdout_context(raw=True):
            while True:
                try:
                    self.cli.run()
                    doc = self.cli.return_value()
                    if doc is None:
                        return
                    cmd = shlex.split(doc.text)
                    app.buffer.reset(append_to_history=True)

                    if not cmd:
                        continue
                    elif cmd[0] in ('exit', 'quit'):
                        self.q.put(Exit())
                        return
                    elif cmd[0] == 'help':
                        print('Help text forthcoming.')
                    elif cmd[0] == 'skip':
                        self.q.put(Skip())
                    elif cmd[0] == 'set':
                        self.q.put(Set(cmd[1], ast.literal_eval(' '.join(cmd[2:]))))
                    else:
                        print('Unknown command. Try \'help\'.')
                except KeyboardInterrupt:
                    continue
                except EOFError:
                    self.q.put(Exit())
                    return
                except Exception as err:
                    print(err)
                    self.q.put(Exit())
                    return
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def init_prompt_toolkit_cli(self):
        if self.simple_prompt:
            # Fall back to plain non-interactive output for tests.
            # This is very limited, and only accepts a single line.
            def prompt():
                return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
            self.prompt_for_code = prompt
            return

        # Set up keyboard shortcuts
        kbmanager = KeyBindingManager.for_prompt(
            enable_open_in_editor=self.extra_open_editor_shortcuts,
        )
        register_ipython_shortcuts(kbmanager.registry, self)

        # Pre-populate history from IPython's history database
        history = InMemoryHistory()
        last_cell = u""
        for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
                                                        include_latest=True):
            # Ignore blank lines and consecutive duplicates
            cell = cell.rstrip()
            if cell and (cell != last_cell):
                history.append(cell)
                last_cell = cell

        self._style = self._make_style_from_name_or_cls(self.highlighting_style)
        style = DynamicStyle(lambda: self._style)

        editing_mode = getattr(EditingMode, self.editing_mode.upper())

        def patch_stdout(**kwargs):
            return self.pt_cli.patch_stdout_context(**kwargs)

        self._pt_app = create_prompt_application(
                            editing_mode=editing_mode,
                            key_bindings_registry=kbmanager.registry,
                            history=history,
                            completer=IPythonPTCompleter(shell=self,
                                                    patch_stdout=patch_stdout),
                            enable_history_search=True,
                            style=style,
                            mouse_support=self.mouse_support,
                            **self._layout_options()
        )
        self._eventloop = create_eventloop(self.inputhook)
        self.pt_cli = CommandLineInterface(
            self._pt_app, eventloop=self._eventloop,
            output=create_output(true_color=self.true_color))
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def init_prompt_toolkit_cli(self):
        if self.simple_prompt:
            # Fall back to plain non-interactive output for tests.
            # This is very limited, and only accepts a single line.
            def prompt():
                return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
            self.prompt_for_code = prompt
            return

        # Set up keyboard shortcuts
        kbmanager = KeyBindingManager.for_prompt()
        register_ipython_shortcuts(kbmanager.registry, self)

        # Pre-populate history from IPython's history database
        history = InMemoryHistory()
        last_cell = u""
        for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
                                                        include_latest=True):
            # Ignore blank lines and consecutive duplicates
            cell = cell.rstrip()
            if cell and (cell != last_cell):
                history.append(cell)

        self._style = self._make_style_from_name(self.highlighting_style)
        style = DynamicStyle(lambda: self._style)

        editing_mode = getattr(EditingMode, self.editing_mode.upper())

        self._pt_app = create_prompt_application(
                            editing_mode=editing_mode,
                            key_bindings_registry=kbmanager.registry,
                            history=history,
                            completer=IPythonPTCompleter(shell=self),
                            enable_history_search=True,
                            style=style,
                            mouse_support=self.mouse_support,
                            **self._layout_options()
        )
        self._eventloop = create_eventloop(self.inputhook)
        self.pt_cli = CommandLineInterface(
            self._pt_app, eventloop=self._eventloop,
            output=create_output(true_color=self.true_color))
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def init_prompt_toolkit_cli(self):
        if self.simple_prompt:
            # Fall back to plain non-interactive output for tests.
            # This is very limited, and only accepts a single line.
            def prompt():
                isp = self.input_splitter
                prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
                prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
                while isp.push_accepts_more():
                    line = cast_unicode_py2(input(prompt_text))
                    isp.push(line)
                    prompt_text = prompt_continuation
                return isp.source_reset()
            self.prompt_for_code = prompt
            return

        # Set up keyboard shortcuts
        kbmanager = KeyBindingManager.for_prompt(
            enable_open_in_editor=self.extra_open_editor_shortcuts,
        )
        register_ipython_shortcuts(kbmanager.registry, self)

        # Pre-populate history from IPython's history database
        history = InMemoryHistory()
        last_cell = u""
        for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
                                                        include_latest=True):
            # Ignore blank lines and consecutive duplicates
            cell = cell.rstrip()
            if cell and (cell != last_cell):
                history.append(cell)
                last_cell = cell

        self._style = self._make_style_from_name_or_cls(self.highlighting_style)
        self.style = DynamicStyle(lambda: self._style)

        editing_mode = getattr(EditingMode, self.editing_mode.upper())

        def patch_stdout(**kwargs):
            return self.pt_cli.patch_stdout_context(**kwargs)

        self._pt_app = create_prompt_application(
                            editing_mode=editing_mode,
                            key_bindings_registry=kbmanager.registry,
                            history=history,
                            completer=IPythonPTCompleter(shell=self,
                                                    patch_stdout=patch_stdout),
                            enable_history_search=True,
                            style=self.style,
                            mouse_support=self.mouse_support,
                            **self._layout_options()
        )
        self._eventloop = create_eventloop(self.inputhook)
        self.pt_cli = CommandLineInterface(
            self._pt_app, eventloop=self._eventloop,
            output=create_output(true_color=self.true_color))