Python prompt_toolkit.shortcuts.PromptSession() Examples

The following are 11 code examples of prompt_toolkit.shortcuts.PromptSession(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module prompt_toolkit.shortcuts , or try the search function .
Example #1
Source File: toolbar.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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") 
Example #2
Source File: inputhook.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #3
Source File: test_cli.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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() 
Example #4
Source File: __init__.py    From edgedb with Apache License 2.0 5 votes vote down vote up
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 
Example #5
Source File: chat-app.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #6
Source File: asyncio-prompt.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #7
Source File: operate-and-get-next.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    session = PromptSession("prompt> ")
    while True:
        session.prompt() 
Example #8
Source File: test_cli.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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() 
Example #9
Source File: rlinit.py    From mec with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #10
Source File: __init__.py    From edgedb with Apache License 2.0 4 votes vote down vote up
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 
Example #11
Source File: main.py    From athenacli with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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
            )