当前位置: 首页>>代码示例>>Python>>正文


Python history.InMemoryHistory类代码示例

本文整理汇总了Python中prompt_toolkit.history.InMemoryHistory的典型用法代码示例。如果您正苦于以下问题:Python InMemoryHistory类的具体用法?Python InMemoryHistory怎么用?Python InMemoryHistory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了InMemoryHistory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: HistoryManager

class HistoryManager(object):
    def __init__(self, *args, **kwargs):
        super(HistoryManager, self).__init__(*args, **kwargs)

        self._history = None
        self.last_cmd = None
        self.db = None

        if HAVE_SQLITE:
            dbpath = os.path.join(
                save_cache_path('graphcli'),
                'history.db'
            )
            self.db = sqlite3.connect(dbpath)
            self.cursor = self.db.cursor()

            self.cursor.execute('''
                CREATE TABLE IF NOT EXISTS graphcli_history (
                    ts INT,
                    cmd TEXT
                )
            ''')

    @property
    def history(self):
        if self._history is None:
            self._history = InMemoryHistory()

            for cmd in self.read_history():
                self._history.append('{0};'.format(cmd))
                self.last_cmd = cmd

        return self._history

    def read_history(self):
        if self.db is not None:
            commands = self.cursor.execute('''
                SELECT cmd FROM graphcli_history
                ORDER BY ts DESC
                LIMIT ?
            ''', (self.history_size,))

            for row in reversed(list(commands)):
                yield row[0]

    def add_to_history(self, cmd):
        if cmd != self.last_cmd:
            if self.db is not None:
                ts = int(time())

                self.cursor.execute('''
                    INSERT INTO graphcli_history VALUES (:ts, :cmd)
                ''', {'ts': ts, 'cmd': cmd})

            self.last_cmd = cmd

    def close(self):
        if self.db is not None:
            self.db.commit()
            self.db.close()
开发者ID:linkdd,项目名称:link.graph,代码行数:60,代码来源:history.py

示例2: init_prompt_toolkit_cli

    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))
开发者ID:BarnetteME1,项目名称:DnD-stuff,代码行数:56,代码来源:interactiveshell.py

示例3: __init__

    def __init__(self, completer, model_completer, docs,
                 input=None, output=None):
        self.completer = completer
        self.model_completer = model_completer
        self.history = InMemoryHistory()
        self.file_history = FileHistory(build_config_file_path('history'))
        self._cli = None
        self._docs = docs
        self.current_docs = u''
        self.refresh_cli = False
        self.key_manager = None
        self._dot_cmd = DotCommandHandler()
        self._env = os.environ.copy()
        self._profile = None
        self._input = input
        self._output = output

        # These attrs come from the config file.
        self.config_obj = None
        self.config_section = None
        self.enable_vi_bindings = None
        self.show_completion_columns = None
        self.show_help = None
        self.theme = None

        self.load_config()
开发者ID:auready,项目名称:aws-shell,代码行数:26,代码来源:app.py

示例4: init_prompt_toolkit_cli

    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 = input(prompt_text)
                    isp.push(line)
                    prompt_text = prompt_continuation
                return isp.source_reset()
            self.prompt_for_code = prompt
            return

        # Set up keyboard shortcuts
        key_bindings = create_ipython_shortcuts(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_string(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())

        self.pt_app = PromptSession(
                            editing_mode=editing_mode,
                            key_bindings=key_bindings,
                            history=history,
                            completer=IPythonPTCompleter(shell=self),
                            enable_history_search = self.enable_history_search,
                            style=self.style,
                            include_default_pygments_style=False,
                            mouse_support=self.mouse_support,
                            enable_open_in_editor=self.extra_open_editor_shortcuts,
                            color_depth=(ColorDepth.TRUE_COLOR if self.true_color else None),
                            **self._extra_prompt_options())
开发者ID:dalejung,项目名称:ipython,代码行数:47,代码来源:interactiveshell.py

示例5: main

def main():
    # Create some history first. (Easy for testing.)
    history = InMemoryHistory()
    history.append_string('import os')
    history.append_string('print("hello")')
    history.append_string('print("world")')
    history.append_string('import path')

    # Print help.
    print('This CLI has fish-style auto-suggestion enable.')
    print('Type for instance "pri", then you\'ll see a suggestion.')
    print('Press the right arrow to insert the suggestion.')
    print('Press Control-C to retry. Control-D to exit.')
    print()

    session = PromptSession(
        history=history,
        auto_suggest=AutoSuggestFromHistory(),
        enable_history_search=True)

    while True:
        try:
            text = session.prompt('Say something: ')
        except KeyboardInterrupt:
            pass  # Ctrl-C pressed. Try again.
        else:
            break

    print('You said: %s' % text)
开发者ID:jonathanslenders,项目名称:python-prompt-toolkit,代码行数:29,代码来源:auto-suggestion.py

示例6: main

def main():
    # Create some history first. (Easy for testing.)
    history = InMemoryHistory()
    history.append_string('import os')
    history.append_string('print("hello")')
    history.append_string('print("world")')
    history.append_string('import path')

    # Print help.
    print('This CLI has up-arrow partial string matching enabled.')
    print('Type for instance "pri" followed by up-arrow and you')
    print('get the last items starting with "pri".')
    print('Press Control-C to retry. Control-D to exit.')
    print()

    session = PromptSession(history=history, enable_history_search=True)

    while True:
        try:
            text = session.prompt('Say something: ')
        except KeyboardInterrupt:
            pass  # Ctrl-C pressed. Try again.
        else:
            break

    print('You said: %s' % text)
开发者ID:jonathanslenders,项目名称:python-prompt-toolkit,代码行数:26,代码来源:up-arrow-partial-string-matching.py

示例7: history

    def history(self):
        if self._history is None:
            self._history = InMemoryHistory()

            for cmd in self.read_history():
                self._history.append('{0};'.format(cmd))
                self.last_cmd = cmd

        return self._history
开发者ID:linkdd,项目名称:link.graph,代码行数:9,代码来源:history.py

示例8: init_prompt_toolkit_cli

    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)
                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())

        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))
开发者ID:briandrawert,项目名称:ipython,代码行数:43,代码来源:interactiveshell.py

示例9: __init__

 def __init__(self, completer, model_completer, docs):
     self.completer = completer
     self.model_completer = model_completer
     self.history = InMemoryHistory()
     self.file_history = FileHistory(build_config_file_path('history'))
     self._cli = None
     self._docs = docs
     self.current_docs = u''
     self.refresh_cli = False
     self._dot_cmd = DotCommandHandler()
     self.load_config()
开发者ID:rmoorman,项目名称:aws-shell,代码行数:11,代码来源:app.py

示例10: main

def main():
    # Create some history first. (Easy for testing.)
    history = InMemoryHistory()
    history.append("import os")
    history.append('print("hello")')
    history.append('print("world")')
    history.append("import path")

    # Print help.
    print("This CLI has up-arrow partial string matching enabled.")
    print('Type for instance "pri" followed by up-arrow and you')
    print('get the last items starting with "pri".')
    print("Press Control-C to retry. Control-D to exit.")
    print()

    text = prompt("Say something: ", history=history, enable_history_search=Always(), on_abort=AbortAction.RETRY)
    print("You said: %s" % text)
开发者ID:henryiii,项目名称:python-prompt-toolkit,代码行数:17,代码来源:up-arrow-partial-string-matching.py

示例11: main

def main():
    # Create some history first. (Easy for testing.)
    history = InMemoryHistory()
    history.append('import os')
    history.append('print("hello")')
    history.append('print("world")')
    history.append('import path')

    # Print help.
    print('This CLI has fish-style auto-suggestion enable.')
    print('Type for instance "pri", then you\'ll see a suggestion.')
    print('Press the right arrow to insert the suggestion.')
    print('Press Control-C to retry. Control-D to exit.')
    print()

    text = prompt('Say something: ', history=history,
                  auto_suggest=AutoSuggestFromHistory(),
                  enable_history_search=True,
                  on_abort=AbortAction.RETRY)
    print('You said: {0!s}'.format(text))
开发者ID:runt18,项目名称:python-prompt-toolkit,代码行数:20,代码来源:auto-suggestion.py

示例12: _history

def _history():
    h = InMemoryHistory()
    h.append_string('line1 first input')
    h.append_string('line2 second input')
    h.append_string('line3 third input')
    return h
开发者ID:jonathanslenders,项目名称:python-prompt-toolkit,代码行数:6,代码来源:test_cli.py

示例13: InMemoryHistory

from prompt_toolkit import prompt
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory

history = InMemoryHistory()
for word in ["apple", "banana", "orange", "grape", "pineapple"]:
    history.append(word)

while True:
    text = prompt('> ', history=history, auto_suggest=AutoSuggestFromHistory())
    print('You said: ', text)
开发者ID:podhmo,项目名称:individual-sandbox,代码行数:11,代码来源:06withhistory.py

示例14: _history

def _history():
    " Prefilled history. "
    history = InMemoryHistory()
    history.append_string('alpha beta gamma delta')
    history.append_string('one two three four')
    return history
开发者ID:tsvenson,项目名称:python-prompt-toolkit,代码行数:6,代码来源:test_yank_nth_arg.py

示例15: init_prompt_toolkit_cli

    def init_prompt_toolkit_cli(self):
        if ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or not sys.stdin.isatty():
            # 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

        kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode)
        insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT)
        # Ctrl+J == Enter, seemingly
        @kbmanager.registry.add_binding(Keys.ControlJ,
                            filter=(HasFocus(DEFAULT_BUFFER)
                                    & ~HasSelection()
                                    & insert_mode
                                   ))
        def _(event):
            b = event.current_buffer
            d = b.document
            if not (d.on_last_line or d.cursor_position_row >= d.line_count
                                           - d.empty_line_count_at_the_end()):
                b.newline()
                return

            status, indent = self.input_splitter.check_complete(d.text)

            if (status != 'incomplete') and b.accept_action.is_returnable:
                b.accept_action.validate_and_handle(event.cli, b)
            else:
                b.insert_text('\n' + (' ' * (indent or 0)))

        @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER))
        def _(event):
            event.current_buffer.reset()

        @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER))
        def _(event):
            if event.current_buffer.document.text:
                event.current_buffer.reset()
            else:
                event.cli.push_focus(DEFAULT_BUFFER)

        supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))

        @kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend)
        def _(event):
            event.cli.suspend_to_background()

        @Condition
        def cursor_in_leading_ws(cli):
            before = cli.application.buffer.document.current_line_before_cursor
            return (not before) or before.isspace()

        # Ctrl+I == Tab
        @kbmanager.registry.add_binding(Keys.ControlI,
                            filter=(HasFocus(DEFAULT_BUFFER)
                                    & ~HasSelection()
                                    & insert_mode
                                    & cursor_in_leading_ws
                                   ))
        def _(event):
            event.current_buffer.insert_text(' ' * 4)

        # 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)

        self._app = create_prompt_application(
                            key_bindings_registry=kbmanager.registry,
                            history=history,
                            completer=IPythonPTCompleter(self.Completer),
                            enable_history_search=True,
                            style=style,
                            mouse_support=self.mouse_support,
                            **self._layout_options()
        )
        self.pt_cli = CommandLineInterface(self._app,
                           eventloop=create_eventloop(self.inputhook))
开发者ID:Katkamaculikova123,项目名称:ipython,代码行数:88,代码来源:ptshell.py


注:本文中的prompt_toolkit.history.InMemoryHistory类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。