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


Python shortcuts.PromptSession方法代码示例

本文整理汇总了Python中prompt_toolkit.shortcuts.PromptSession方法的典型用法代码示例。如果您正苦于以下问题:Python shortcuts.PromptSession方法的具体用法?Python shortcuts.PromptSession怎么用?Python shortcuts.PromptSession使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在prompt_toolkit.shortcuts的用法示例。


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

示例1: interact

# 需要导入模块: from prompt_toolkit import shortcuts [as 别名]
# 或者: from prompt_toolkit.shortcuts import PromptSession [as 别名]
def interact(connection):
    # When a client is connected, erase the screen from the client and say
    # Hello.
    connection.send("Welcome!\n")

    # Display prompt with bottom toolbar.
    animal_completer = WordCompleter(["alligator", "ant"])

    def get_toolbar():
        return "Bottom toolbar..."

    session = PromptSession()
    result = await session.prompt_async(
        "Say something: ", bottom_toolbar=get_toolbar, completer=animal_completer
    )

    connection.send("You said: {}\n".format(result))
    connection.send("Bye.\n") 
开发者ID:prompt-toolkit,项目名称:python-prompt-toolkit,代码行数:20,代码来源:toolbar.py

示例2: main

# 需要导入模块: from prompt_toolkit import shortcuts [as 别名]
# 或者: from prompt_toolkit.shortcuts import PromptSession [as 别名]
def main():
    # Create user interface.
    hello_world_window()

    # Enable threading in GTK. (Otherwise, GTK will keep the GIL.)
    gtk.gdk.threads_init()

    # Read input from the command line, using an event loop with this hook.
    # We use `patch_stdout`, because clicking the button will print something;
    # and that should print nicely 'above' the input line.
    with patch_stdout():
        session = PromptSession(
            "Python >>> ", inputhook=inputhook, lexer=PygmentsLexer(PythonLexer)
        )
        result = session.prompt()
    print("You said: %s" % result) 
开发者ID:prompt-toolkit,项目名称:python-prompt-toolkit,代码行数:18,代码来源:inputhook.py

示例3: test_accept_default

# 需要导入模块: from prompt_toolkit import shortcuts [as 别名]
# 或者: from prompt_toolkit.shortcuts import PromptSession [as 别名]
def test_accept_default():
    """
    Test `prompt(accept_default=True)`.
    """
    inp = create_pipe_input()

    session = PromptSession(input=inp, output=DummyOutput())
    result = session.prompt(default="hello", accept_default=True)
    assert result == "hello"

    # Test calling prompt() for a second time. (We had an issue where the
    # prompt reset between calls happened at the wrong time, breaking this.)
    result = session.prompt(default="world", accept_default=True)
    assert result == "world"

    inp.close() 
开发者ID:prompt-toolkit,项目名称:python-prompt-toolkit,代码行数:18,代码来源:test_cli.py

示例4: prompt

# 需要导入模块: from prompt_toolkit import shortcuts [as 别名]
# 或者: from prompt_toolkit.shortcuts import PromptSession [as 别名]
def prompt(self) -> pt_shortcuts.PromptSession:
        if self._prompt is None:
            # If this exception is thrown it means that the calling
            # code did not call inside the `self.run()` method.
            raise RuntimeError('prompt is not available')
        return self._prompt 
开发者ID:edgedb,项目名称:edgedb,代码行数:8,代码来源:__init__.py

示例5: interact

# 需要导入模块: from prompt_toolkit import shortcuts [as 别名]
# 或者: from prompt_toolkit.shortcuts import PromptSession [as 别名]
def interact(connection):
    write = connection.send
    prompt_session = PromptSession()

    # When a client is connected, erase the screen from the client and say
    # Hello.
    clear()
    write("Welcome to our chat application!\n")
    write("All connected clients will receive what you say.\n")

    name = await prompt_session.prompt_async(message="Type your name: ")

    # Random color.
    color = random.choice(COLORS)
    _connection_to_color[connection] = color

    # Send 'connected' message.
    _send_to_everyone(connection, name, "(connected)", color)

    # Prompt.
    prompt_msg = HTML('<reverse fg="{}">[{}]</reverse> &gt; ').format(color, name)

    _connections.append(connection)
    try:
        # Set Application.
        while True:
            try:
                result = await prompt_session.prompt_async(message=prompt_msg)
                _send_to_everyone(connection, name, result, color)
            except KeyboardInterrupt:
                pass
    except EOFError:
        _send_to_everyone(connection, name, "(leaving)", color)
    finally:
        _connections.remove(connection) 
开发者ID:prompt-toolkit,项目名称:python-prompt-toolkit,代码行数:37,代码来源:chat-app.py

示例6: interactive_shell

# 需要导入模块: from prompt_toolkit import shortcuts [as 别名]
# 或者: from prompt_toolkit.shortcuts import PromptSession [as 别名]
def interactive_shell():
    """
    Like `interactive_shell`, but doing things manual.
    """
    # Create Prompt.
    session = PromptSession("Say something: ")

    # Run echo loop. Read text from stdin, and reply it back.
    while True:
        try:
            result = await session.prompt_async()
            print('You said: "{0}"'.format(result))
        except (EOFError, KeyboardInterrupt):
            return 
开发者ID:prompt-toolkit,项目名称:python-prompt-toolkit,代码行数:16,代码来源:asyncio-prompt.py

示例7: main

# 需要导入模块: from prompt_toolkit import shortcuts [as 别名]
# 或者: from prompt_toolkit.shortcuts import PromptSession [as 别名]
def main():
    session = PromptSession("prompt> ")
    while True:
        session.prompt() 
开发者ID:prompt-toolkit,项目名称:python-prompt-toolkit,代码行数:6,代码来源:operate-and-get-next.py

示例8: _feed_cli_with_input

# 需要导入模块: from prompt_toolkit import shortcuts [as 别名]
# 或者: from prompt_toolkit.shortcuts import PromptSession [as 别名]
def _feed_cli_with_input(
    text,
    editing_mode=EditingMode.EMACS,
    clipboard=None,
    history=None,
    multiline=False,
    check_line_ending=True,
    key_bindings=None,
):
    """
    Create a Prompt, feed it with the given user input and return the CLI
    object.

    This returns a (result, Application) tuple.
    """
    # If the given text doesn't end with a newline, the interface won't finish.
    if check_line_ending:
        assert text.endswith("\r")

    inp = create_pipe_input()

    try:
        inp.send_text(text)
        session = PromptSession(
            input=inp,
            output=DummyOutput(),
            editing_mode=editing_mode,
            history=history,
            multiline=multiline,
            clipboard=clipboard,
            key_bindings=key_bindings,
        )

        result = session.prompt()
        return session.default_buffer.document, session.app

    finally:
        inp.close() 
开发者ID:prompt-toolkit,项目名称:python-prompt-toolkit,代码行数:40,代码来源:test_cli.py

示例9: prompt

# 需要导入模块: from prompt_toolkit import shortcuts [as 别名]
# 或者: from prompt_toolkit.shortcuts import PromptSession [as 别名]
def prompt(session):
    '''
    mec prompt
    '''
    cmd_list = readline_init(session)

    # cook our completions
    completion_dict = dict.fromkeys(cmd_list)
    completion_dict["target"] = dict.fromkeys(os.listdir("./data"))
    completion_dict["set"] = dict.fromkeys(["auto-update", "proxy-pool"])
    completion_dict["set"]["auto-update"] = dict.fromkeys(["True", "False"])

    mec_completer = NestedCompleter.from_nested_dict(completion_dict)
    mec_ps = ANSI(colors.CYAN + colors.BOLD + "\nmec > " + colors.END)

    cmd_autosuggest = ThreadedAutoSuggest(MecAutoSuggest(completions=cmd_list))

    try:
        mecprompt = PromptSession(message=mec_ps,
                                  mouse_support=True,
                                  history=FileHistory(HISTFILE),
                                  completer=mec_completer,
                                  complete_while_typing=True,
                                  reserve_space_for_menu=2,
                                  auto_suggest=cmd_autosuggest).prompt()
    except termios.error as err:
        colors.colored_print(f"[-] Fatal error: {err}", color_code=colors.RED)
        os.system("mec stop")

    return mecprompt 
开发者ID:jm33-m0,项目名称:mec,代码行数:32,代码来源:rlinit.py

示例10: build_propmpt

# 需要导入模块: from prompt_toolkit import shortcuts [as 别名]
# 或者: from prompt_toolkit.shortcuts import PromptSession [as 别名]
def build_propmpt(self) -> pt_shortcuts.PromptSession:
        history = pt_history.FileHistory(
            os.path.expanduser('~/.edgedbhistory'))

        bindings = pt_key_binding.KeyBindings()
        handle = bindings.add

        @handle('f3')  # type: ignore
        def _mode_toggle(event: Any) -> None:
            self.context.toggle_query_mode()

        @handle('f4')  # type: ignore
        def _implicit_toggle(event: Any) -> None:
            self.context.toggle_implicit()

        @handle('f5')  # type: ignore
        def _introspect_toggle(event: Any) -> None:
            self.context.toggle_introspect_types()

            if self.context.introspect_types:
                self.ensure_connection()
                self.introspect_db(self.connection)
            else:
                self.context.typenames = None

        @handle('tab')  # type: ignore
        def _tab(event: Any) -> None:
            b = prompt.app.current_buffer
            before_cursor = b.document.current_line_before_cursor
            if b.text and (not before_cursor or before_cursor.isspace()):
                b.insert_text('    ')

        prompt = pt_shortcuts.PromptSession(
            lexer=pt_lexers.PygmentsLexer(eql_pygments.EdgeQLLexer),
            include_default_pygments_style=False,

            completer=pt_complete.DummyCompleter(),
            reserve_space_for_menu=6,

            message=self.get_prompt_tokens,
            prompt_continuation=self.get_continuation_tokens,
            bottom_toolbar=self.get_toolbar_tokens,
            multiline=is_multiline,
            history=history,
            complete_while_typing=pt_filters.Always(),
            key_bindings=bindings,
            style=self.style,
            editing_mode=pt_enums.EditingMode.VI,
            search_ignore_case=True,
        )

        return prompt 
开发者ID:edgedb,项目名称:edgedb,代码行数:54,代码来源:__init__.py

示例11: _build_prompt_app

# 需要导入模块: from prompt_toolkit import shortcuts [as 别名]
# 或者: from prompt_toolkit.shortcuts import PromptSession [as 别名]
def _build_prompt_app(self, history):
        key_bindings = cli_bindings(self)

        def get_message():
            prompt = self.get_prompt(self.prompt)
            if len(prompt) > self.MAX_LEN_PROMPT:
                prompt = self.get_prompt('\\r:\\d> ')
            return [('class:prompt', prompt)]

        def get_continuation(width, line_number, is_soft_wrap):
            continuation = ' ' * (width -1) + ' '
            return [('class:continuation', continuation)]

        def show_suggestion_tip():
            return self.iterations < 2

        get_toolbar_tokens = create_toolbar_tokens_func(
            self, show_suggestion_tip)

        with self._completer_lock:
            if self.key_bindings == 'vi':
                editing_mode = EditingMode.VI
            else:
                editing_mode = EditingMode.EMACS

            self.prompt_app = PromptSession(
                lexer=PygmentsLexer(Lexer),
                reserve_space_for_menu=self.get_reserved_space(),
                message=get_message,
                prompt_continuation=get_continuation,
                bottom_toolbar=get_toolbar_tokens,
                complete_style=CompleteStyle.COLUMN,
                input_processors=[ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()
                )],
                tempfile_suffix='.sql',
                completer=DynamicCompleter(lambda: self.completer),
                history=history,
                auto_suggest=AutoSuggestFromHistory(),
                complete_while_typing=True,
                multiline=cli_is_multiline(self),
                style=style_factory(self.syntax_style, self.cli_style),
                include_default_pygments_style=False,
                key_bindings=key_bindings,
                enable_open_in_editor=True,
                enable_system_prompt=True,
                editing_mode=editing_mode,
                search_ignore_case=True
            ) 
开发者ID:dbcli,项目名称:athenacli,代码行数:53,代码来源:main.py


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