python-prompt-toolkit
Library for building powerful interactive command line applications in Python
Top Related Projects
Library for building powerful interactive command line applications in Python
Python composable command line interface toolkit
A cross platform package to do curses-like operations, plus higher level APIs and widgets to create text UIs and ASCII art animations
Rich is a Python library for rich text and beautiful formatting in the terminal.
The lean application framework for Python. Build sophisticated user interfaces with a simple Python API. Run your apps in the terminal and a web browser.
Quick Overview
The prompt-toolkit
is a Python library that provides a set of tools for building interactive command-line interfaces (CLIs) and terminal-based applications. It offers a flexible and customizable way to create rich and responsive user interfaces, making it a popular choice for developers working on terminal-based applications.
Pros
- Flexibility: The
prompt-toolkit
provides a wide range of features and customization options, allowing developers to create highly tailored and interactive command-line interfaces. - Cross-platform compatibility: The library works across multiple platforms, including Windows, macOS, and Linux, making it a versatile choice for building terminal-based applications.
- Powerful input handling: The
prompt-toolkit
offers advanced input handling capabilities, including support for auto-completion, syntax highlighting, and key bindings. - Extensive documentation: The project has comprehensive documentation, making it easy for developers to get started and understand the various features and functionalities of the library.
Cons
- Learning curve: While the
prompt-toolkit
is powerful, it may have a steeper learning curve compared to simpler command-line interface libraries, especially for developers new to building terminal-based applications. - Performance overhead: Depending on the complexity of the application, the
prompt-toolkit
may introduce some performance overhead, which could be a concern for highly interactive or resource-intensive terminal-based applications. - Limited support for older Python versions: The library may not provide full support for older versions of Python, which could be a limitation for developers working on legacy systems.
- Dependency management: The
prompt-toolkit
has several dependencies, which may require additional effort to manage and maintain in some projects.
Code Examples
Here are a few examples of how to use the prompt-toolkit
library:
- Basic Prompt:
from prompt_toolkit import prompt
name = prompt("What is your name? ")
print(f"Hello, {name}!")
This code creates a simple prompt that asks the user for their name and then prints a greeting.
- Auto-completion:
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter
animals = ["dog", "cat", "bird", "elephant", "giraffe"]
animal_completer = WordCompleter(animals)
animal = prompt("What is your favorite animal? ", completer=animal_completer)
print(f"Your favorite animal is {animal}.")
This example demonstrates how to use the WordCompleter
to provide auto-completion for a list of animals.
- Syntax Highlighting:
from prompt_toolkit import prompt
from prompt_toolkit.lexers import PythonLexer
code = prompt("Enter some Python code: ", lexer=PythonLexer())
print(f"You entered:\n{code}")
This code creates a prompt that provides syntax highlighting for Python code using the PythonLexer
.
- Key Bindings:
from prompt_toolkit import prompt
from prompt_toolkit.key_binding import KeyBindings
bindings = KeyBindings()
@bindings.add("c-t")
def _(event):
print("Ctrl+T was pressed!")
name = prompt("What is your name? ", key_bindings=bindings)
print(f"Hello, {name}!")
This example demonstrates how to create custom key bindings using the KeyBindings
class, in this case, binding the "Ctrl+T" combination to a custom action.
Getting Started
To get started with the prompt-toolkit
library, follow these steps:
- Install the library using pip:
pip install prompt-toolkit
- Import the necessary modules from the
prompt-toolkit
library:
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.lexers import PythonLexer
from prompt_toolkit.key_binding import KeyBindings
-
Use the various features of the
prompt-toolkit
library to build your interactive command-line interface. Refer to the code examples above for some basic usage patterns. -
Explore the official documentation to learn more about the library's advanced features and customization options.
Competitor Comparisons
Library for building powerful interactive command line applications in Python
Pros of python-prompt-toolkit
- Identical functionality and features
- Same level of community support and maintenance
- Consistent documentation and examples
Cons of python-prompt-toolkit
- No significant differences in drawbacks
- Equivalent performance characteristics
- Similar learning curve and complexity
Code Comparison
Both repositories contain the same codebase, so there are no differences to highlight in a code comparison. For example, both would include the same basic usage:
from prompt_toolkit import prompt
user_input = prompt('Enter your name: ')
print(f'Hello, {user_input}!')
Summary
The comparison between prompt-toolkit/python-prompt-toolkit and prompt-toolkit/python-prompt-toolkit reveals that they are, in fact, the same repository. There are no distinguishing features, pros, or cons between them as they refer to the identical project. The python-prompt-toolkit is a powerful library for building interactive command-line applications in Python, offering advanced features like syntax highlighting, multi-line editing, and auto-completion. Users can expect the same functionality, performance, and community support regardless of which URL they use to access the repository.
Python composable command line interface toolkit
Pros of Click
- Simpler and more straightforward API for creating command-line interfaces
- Extensive documentation and a large, active community
- Built-in support for generating command-line help messages
Cons of Click
- Less flexible for creating complex, interactive prompts
- Limited support for real-time input validation and auto-completion
- Focused primarily on command-line argument parsing rather than interactive prompts
Code Comparison
Click:
import click
@click.command()
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(name):
click.echo(f"Hello, {name}!")
Python Prompt Toolkit:
from prompt_toolkit import prompt
def hello():
name = prompt('Your name: ')
print(f"Hello, {name}!")
Python Prompt Toolkit offers more advanced features for creating interactive prompts, such as syntax highlighting, auto-completion, and multi-line editing. Click, on the other hand, provides a simpler interface for creating command-line tools with options and arguments. Choose Click for straightforward command-line applications, and Python Prompt Toolkit for more complex, interactive command-line interfaces.
A cross platform package to do curses-like operations, plus higher level APIs and widgets to create text UIs and ASCII art animations
Pros of asciimatics
- Offers more advanced text-based UI elements like widgets and forms
- Provides cross-platform support for creating animations and visual effects
- Includes built-in support for color and styling
Cons of asciimatics
- Steeper learning curve due to more complex API
- Less focused on command-line interfaces and more on full-screen applications
- Fewer updates and potentially less active development
Code Comparison
asciimatics:
from asciimatics.screen import Screen
from asciimatics.scene import Scene
from asciimatics.effects import Cycle, Stars
from asciimatics.renderers import FigletText
def demo(screen):
effects = [
Cycle(
screen,
FigletText("ASCIIMATICS", font='big'),
int(screen.height / 2 - 8)),
Stars(screen, 200)
]
screen.play([Scene(effects, 500)])
Screen.wrapper(demo)
python-prompt-toolkit:
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter
html_completer = WordCompleter(['<html>', '<body>', '<head>', '<title>'])
text = prompt('Enter HTML: ', completer=html_completer)
print('You entered:', text)
Rich is a Python library for rich text and beautiful formatting in the terminal.
Pros of Rich
- Offers a wider range of rich text formatting options, including colors, styles, and tables
- Provides built-in progress bars, syntax highlighting, and markdown rendering
- Easier to use for complex console output with less code
Cons of Rich
- Larger library size and potentially slower performance for simple tasks
- Less focused on interactive input handling compared to Python Prompt Toolkit
- May be overkill for projects that only need basic console output
Code Comparison
Rich:
from rich import print
print("[bold red]Hello[/bold red] [green]World[/green]!")
Python Prompt Toolkit:
from prompt_toolkit import print_formatted_text, HTML
print_formatted_text(HTML('<b><red>Hello</red></b> <green>World</green>!'))
Both libraries offer ways to create formatted console output, but Rich provides a more concise and intuitive syntax for complex formatting. Python Prompt Toolkit excels in creating interactive command-line interfaces and handling user input, while Rich focuses more on rich text output and visualization in the console.
The lean application framework for Python. Build sophisticated user interfaces with a simple Python API. Run your apps in the terminal and a web browser.
Pros of Textual
- Offers a more comprehensive framework for building full-fledged TUI applications
- Provides a rich set of pre-built widgets and layouts for complex interfaces
- Supports modern features like animations and responsive design
Cons of Textual
- Steeper learning curve due to its more extensive API and concepts
- May be overkill for simple command-line interfaces or basic prompts
- Requires more setup and boilerplate code for basic functionality
Code Comparison
Textual example:
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer
class MyApp(App):
def compose(self) -> ComposeResult:
yield Header()
yield Footer()
if __name__ == "__main__":
app = MyApp()
app.run()
Python Prompt Toolkit example:
from prompt_toolkit import prompt
user_input = prompt('Enter your name: ')
print(f"Hello, {user_input}!")
Summary
Textual is better suited for complex, feature-rich TUI applications, while Python Prompt Toolkit excels in creating simple, interactive command-line interfaces and prompts. Textual offers more advanced features but requires more setup, whereas Python Prompt Toolkit provides a straightforward API for basic input handling and formatting.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Python Prompt Toolkit
|AppVeyor| |PyPI| |RTD| |License| |Codecov|
.. image :: https://github.com/prompt-toolkit/python-prompt-toolkit/raw/master/docs/images/logo_400px.png
prompt_toolkit
is a library for building powerful interactive command line applications in Python.
Read the documentation on readthedocs <http://python-prompt-toolkit.readthedocs.io/en/stable/>
_.
Gallery
ptpython <http://github.com/prompt-toolkit/ptpython/>
_ is an interactive
Python Shell, build on top of prompt_toolkit
.
.. image :: https://github.com/prompt-toolkit/python-prompt-toolkit/raw/master/docs/images/ptpython.png
More examples <https://python-prompt-toolkit.readthedocs.io/en/stable/pages/gallery.html>
_
prompt_toolkit features
prompt_toolkit
could be a replacement for GNU readline <https://tiswww.case.edu/php/chet/readline/rltop.html>
_, but it can be much
more than that.
Some features:
- Pure Python.
- Syntax highlighting of the input while typing. (For instance, with a Pygments lexer.)
- Multi-line input editing.
- Advanced code completion.
- Both Emacs and Vi key bindings. (Similar to readline.)
- Even some advanced Vi functionality, like named registers and digraphs.
- Reverse and forward incremental search.
- Works well with Unicode double width characters. (Chinese input.)
- Selecting text for copy/paste. (Both Emacs and Vi style.)
- Support for
bracketed paste <https://cirw.in/blog/bracketed-paste>
_. - Mouse support for cursor positioning and scrolling.
- Auto suggestions. (Like
fish shell <http://fishshell.com/>
_.) - Multiple input buffers.
- No global state.
- Lightweight, the only dependencies are Pygments and wcwidth.
- Runs on Linux, OS X, FreeBSD, OpenBSD and Windows systems.
- And much more...
Feel free to create tickets for bugs and feature requests, and create pull requests if you have nice patches that you would like to share with others.
Installation
::
pip install prompt_toolkit
For Conda, do:
::
conda install -c https://conda.anaconda.org/conda-forge prompt_toolkit
About Windows support
prompt_toolkit
is cross platform, and everything that you build on top
should run fine on both Unix and Windows systems. Windows support is best on
recent Windows 10 builds, for which the command line window supports vt100
escape sequences. (If not supported, we fall back to using Win32 APIs for color
and cursor movements).
It's worth noting that the implementation is a "best effort of what is possible". Both Unix and Windows terminals have their limitations. But in general, the Unix experience will still be a little better.
Getting started
The most simple example of the library would look like this:
.. code:: python
from prompt_toolkit import prompt
if __name__ == '__main__':
answer = prompt('Give me some input: ')
print('You said: %s' % answer)
For more complex examples, have a look in the examples
directory. All
examples are chosen to demonstrate only one thing. Also, don't be afraid to
look at the source code. The implementation of the prompt
function could be
a good start.
Philosophy
The source code of prompt_toolkit
should be readable, concise and
efficient. We prefer short functions focusing each on one task and for which
the input and output types are clearly specified. We mostly prefer composition
over inheritance, because inheritance can result in too much functionality in
the same object. We prefer immutable objects where possible (objects don't
change after initialization). Reusability is important. We absolutely refrain
from having a changing global state, it should be possible to have multiple
independent instances of the same code in the same process. The architecture
should be layered: the lower levels operate on primitive operations and data
structures giving -- when correctly combined -- all the possible flexibility;
while at the higher level, there should be a simpler API, ready-to-use and
sufficient for most use cases. Thinking about algorithms and efficiency is
important, but avoid premature optimization.
Projects using prompt_toolkit <PROJECTS.rst>
_
Special thanks to
Pygments <http://pygments.org/>
_: Syntax highlighter.wcwidth <https://github.com/jquast/wcwidth>
_: Determine columns needed for a wide characters.
.. |PyPI| image:: https://img.shields.io/pypi/v/prompt_toolkit.svg :target: https://pypi.python.org/pypi/prompt-toolkit/ :alt: Latest Version
.. |AppVeyor| image:: https://ci.appveyor.com/api/projects/status/32r7s2skrgm9ubva?svg=true :target: https://ci.appveyor.com/project/prompt-toolkit/python-prompt-toolkit/
.. |RTD| image:: https://readthedocs.org/projects/python-prompt-toolkit/badge/ :target: https://python-prompt-toolkit.readthedocs.io/en/master/
.. |License| image:: https://img.shields.io/github/license/prompt-toolkit/python-prompt-toolkit.svg :target: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/LICENSE
.. |Codecov| image:: https://codecov.io/gh/prompt-toolkit/python-prompt-toolkit/branch/master/graphs/badge.svg?style=flat :target: https://codecov.io/gh/prompt-toolkit/python-prompt-toolkit/
Top Related Projects
Library for building powerful interactive command line applications in Python
Python composable command line interface toolkit
A cross platform package to do curses-like operations, plus higher level APIs and widgets to create text UIs and ASCII art animations
Rich is a Python library for rich text and beautiful formatting in the terminal.
The lean application framework for Python. Build sophisticated user interfaces with a simple Python API. Run your apps in the terminal and a web browser.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot