Library for building powerful interactive command lines in Python
npx @tessl/cli install tessl/pypi-prompt-toolkit@3.0.0A comprehensive Python library for building powerful interactive command-line applications. Prompt-toolkit provides advanced features including syntax highlighting, multi-line input editing, code completion, both Emacs and Vi key bindings, reverse and forward incremental search, Unicode support, text selection for copy/paste, bracketed paste support, mouse support, auto-suggestions, multiple input buffers, and cross-platform compatibility. It serves as a modern replacement for GNU readline while offering significantly more functionality.
pip install prompt_toolkitimport prompt_toolkitMost common imports for basic usage:
from prompt_toolkit import prompt, PromptSession
from prompt_toolkit import print_formatted_text
from prompt_toolkit.application import ApplicationFor advanced formatting:
from prompt_toolkit.formatted_text import HTML, ANSI
from prompt_toolkit.styles import Stylefrom prompt_toolkit import prompt
# Basic input prompt
answer = prompt('Give me some input: ')
print('You said:', answer)
# Prompt with default value
answer = prompt('Enter name: ', default='John')
# Multi-line input
text = prompt('Enter multi-line text (press ESC then Enter to finish): ',
multiline=True)from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import HTML, ANSI
from prompt_toolkit.styles import Style
# Print with HTML-like formatting
print_formatted_text(HTML('<b>Bold</b> and <i>italic</i> text'))
# Print with ANSI sequences
print_formatted_text(ANSI('\x1b[31mRed text\x1b[0m'))
# Print with custom styles
style = Style.from_dict({
'title': '#ff0066 bold',
'subtitle': '#44ff44 italic'
})
print_formatted_text(HTML('<title>Hello</title> <subtitle>World</subtitle>'),
style=style)from prompt_toolkit import PromptSession
from prompt_toolkit.history import FileHistory
from prompt_toolkit.completion import WordCompleter
# Create reusable prompt session
session = PromptSession(
history=FileHistory('.myhistory'),
auto_suggest=AutoSuggestFromHistory(),
completer=WordCompleter(['hello', 'world', 'python'])
)
while True:
try:
text = session.prompt('> ')
print('You entered:', text)
except (EOFError, KeyboardInterrupt):
breakPrompt-toolkit follows a layered, component-based architecture:
This design provides maximum flexibility while maintaining clean separation of concerns, enabling everything from simple prompts to complex interactive applications.
Framework for building full-featured interactive terminal applications with event loops, layouts, and user interfaces.
class Application:
def __init__(
self,
layout=None,
style=None,
key_bindings=None,
clipboard=None,
full_screen=False,
mouse_support=False,
**kwargs
): ...
def run(self, pre_run=None, set_exception_handler=True): ...
def run_async(self, pre_run=None, set_exception_handler=True): ...
def exit(self, result=None, exception=None, style=""): ...
def get_app(): ...
def get_app_or_none(): ...Simple prompt functions and advanced prompt sessions with history, completion, and validation.
def prompt(
message="",
default="",
password=False,
multiline=False,
complete_style=CompleteStyle.COLUMN,
history=None,
auto_suggest=None,
completer=None,
validator=None,
**kwargs
): ...
class PromptSession:
def __init__(
self,
message="",
multiline=False,
complete_style=CompleteStyle.COLUMN,
history=None,
auto_suggest=None,
completer=None,
validator=None,
**kwargs
): ...
def prompt(self, message=None, **kwargs): ...Comprehensive layout system with containers, windows, controls, and widgets for building complex interfaces.
class Layout:
def __init__(self, container, focused_element=None): ...
class HSplit:
def __init__(self, children, **kwargs): ...
class VSplit:
def __init__(self, children, **kwargs): ...
class Window:
def __init__(self, content=None, **kwargs): ...
class BufferControl:
def __init__(self, buffer=None, **kwargs): ...Rich text formatting with HTML-like syntax, ANSI sequences, and CSS-like styling with Pygments integration.
def print_formatted_text(
*values,
sep=" ",
end="\n",
file=None,
flush=False,
style=None,
output=None,
color_depth=None,
style_transformation=None,
include_default_pygments_style=None
): ...
class HTML:
def __init__(self, value): ...
class ANSI:
def __init__(self, value): ...
class Style:
@classmethod
def from_dict(cls, style_dict): ...Configurable key binding system supporting Vi and Emacs editing modes with customizable key mappings.
class KeyBindings:
def __init__(self): ...
def add(self, *keys, **kwargs): ...
class KeyPress:
def __init__(self, key, data=""): ...
def load_vi_bindings(): ...
def load_emacs_bindings(): ...Auto-completion system with built-in completers for files, words, and custom data, plus validation framework.
class Completer:
def get_completions(self, document, complete_event): ...
class Completion:
def __init__(
self,
text,
start_position=0,
display=None,
display_meta=None,
style="",
selected_style=""
): ...
class Validator:
def validate(self, document): ...
class ValidationError(Exception):
def __init__(self, cursor_position=0, message=""): ...from typing import Optional, List, Dict, Any, Callable, Union
from prompt_toolkit.filters import FilterOrBool
# Application result type
AppResult = Any
# Layout dimension type
AnyDimension = Union[None, int, Dimension]
# Formatted text types
AnyFormattedText = Union[str, List[Tuple[str, str]], HTML, ANSI, FormattedText]
StyleAndTextTuples = List[Tuple[str, str]]
# Filter type for conditional behavior
FilterOrBool = Union[bool, Filter]class Document:
def __init__(self, text="", cursor_position=None): ...
@property
def text(self) -> str: ...
@property
def cursor_position(self) -> int: ...
@property
def current_line(self) -> str: ...
class Buffer:
def __init__(
self,
document=None,
multiline=True,
read_only=False,
history=None,
completer=None,
validator=None,
**kwargs
): ...class CompleteEvent:
def __init__(self, text_inserted=False, completion_requested=False): ...
# Completion style enumeration
class CompleteStyle(Enum):
COLUMN = "column"
MULTI_COLUMN = "multi-column"
READLINE_LIKE = "readline-like"class Keys:
# Common keys
ControlA = "c-a"
ControlC = "c-c"
ControlD = "c-d"
Enter = "\r"
Escape = "\x1b"
Backspace = "\x7f"
Delete = "\x1b[3~"
# Function keys
F1 = "\x1bOP"
F2 = "\x1bOQ"
# Arrow keys
Up = "\x1b[A"
Down = "\x1b[B"
Left = "\x1b[D"
Right = "\x1b[C"
class EditingMode(Enum):
EMACS = "EMACS"
VI = "VI"