Docsity

python-prompt-toolkit.pdf, Study notes of History

Partial preview of the text

Download python-prompt-toolkit.pdf and more Study notes History in PDF only on Docsity!

prompt 𝑡𝑜𝑜𝑙𝑘𝑖𝑡𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛

Release 3.0.

Jonathan Slenders

Apr 04, 2022

ii

prompt 𝑡𝑜𝑜𝑙𝑘𝑖𝑡𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛, 𝑅𝑒𝑙𝑒𝑎𝑠𝑒 3. 0. 29

Warning: Notice that this is the prompt_toolkit 3.0 documentation. It is mostly compatible with the 2.0 branch. The difference is that prompt_toolkit 3.0 requires at least Python 3.6. On the plus side, it uses asyncio natively (rather than it’s own event loop), and we have type annotations everywhere.

prompt_toolkit is a library for building powerful interactive command line and terminal applications in Python.

It can be a very advanced pure Python replacement for GNU readline, but it can also be used for building full screen applications.

Some features:

  • Syntax highlighting of the input while typing. (For instance, with a Pygments lexer.)
  • Multi-line input editing.
  • Advanced code completion.
  • Selecting text for copy/paste. (Both Emacs and Vi style.)
  • Mouse support for cursor positioning and scrolling.
  • Auto suggestions. (Like fish shell.)
  • No global state.

Like readline:

  • Both Emacs and Vi key bindings.
  • Reverse and forward incremental search.
  • Works well with Unicode double width characters. (Chinese input.)

Works everywhere:

  • Pure Python. Runs on all Python versions starting at Python 3.6. (Python 2.6 - 3.x is supported in prompt_toolkit 2.0; not 3.0).
  • Runs on Linux, OS X, OpenBSD and Windows systems.
  • Lightweight, the only dependencies are Pygments and wcwidth.
  • No assumptions about I/O are made. Every prompt_toolkit application should also run in a telnet/ssh server or an asyncio process.

CONTENTS 1

CHAPTER

ONE

GETTING STARTED

Go to getting started and build your first prompt. Issues are tracked on the Github project.

prompt 𝑡𝑜𝑜𝑙𝑘𝑖𝑡𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛, 𝑅𝑒𝑙𝑒𝑎𝑠𝑒 3. 0. 29

4 Chapter 1. Getting started

prompt 𝑡𝑜𝑜𝑙𝑘𝑖𝑡𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛, 𝑅𝑒𝑙𝑒𝑎𝑠𝑒 3. 0. 29

6 Chapter 2. Thanks to:

CHAPTER

THREE

TABLE OF CONTENTS

3.1 Gallery

Showcase, demonstrating the possibilities of prompt_toolkit.

3.1.1 Ptpython, a Python REPL

The prompt:

The configuration menu of ptpython.

The history page with its help. (This is a full-screen layout.)

prompt 𝑡𝑜𝑜𝑙𝑘𝑖𝑡𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛, 𝑅𝑒𝑙𝑒𝑎𝑠𝑒 3. 0. 29

3.1.2 Pyvim, a Vim clone

3.1. Gallery 9

prompt 𝑡𝑜𝑜𝑙𝑘𝑖𝑡𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛, 𝑅𝑒𝑙𝑒𝑎𝑠𝑒 3. 0. 29

3.1.3 Pymux, a terminal multiplexer (like tmux) in Python

3.2 Getting started

3.2.1 Installation

pip install prompt_toolkit

For Conda, do:

conda install -c https://conda.anaconda.org/conda-forge prompt_toolkit

3.2.2 Several use cases: prompts versus full screen terminal applications

prompt_toolkit was in the first place meant to be a replacement for readline. However, when it became more mature, we realised that all the components for full screen applications are there and prompt_toolkit is very capable of handling many use situations. Pyvim and pymux are examples of full screen applications.

10 Chapter 3. Table of contents

prompt 𝑡𝑜𝑜𝑙𝑘𝑖𝑡𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛, 𝑅𝑒𝑙𝑒𝑎𝑠𝑒 3. 0. 29

3.2.4 Learning prompt_toolkit

In order to learn and understand prompt_toolkit , it is best to go through the all sections in the order below. Also don’t forget to have a look at all the examples in the repository.

  • First, learn how to print text. This is important, because it covers how to use “formatted text”, which is something you’ll use whenever you want to use colors anywhere.
  • Secondly, go through the asking for input section. This is useful for almost any use case, even for full screen applications. It covers autocompletions, syntax highlighting, key bindings, and so on.
  • Then, learn about Dialogs , which is easy and fun.
  • Finally, learn about full screen applications and read through the advanced topics.

3.3 Upgrading

3.3.1 Upgrading to prompt_toolkit 2.

Prompt_toolkit 2.0 is not compatible with 1.0, however you probably want to upgrade your applications. This page explains why we have these differences and how to upgrade.

If you experience some difficulties or you feel that some information is missing from this page, don’t hesitate to open a GitHub issue for help.

Why all these breaking changes?

After more and more custom prompt_toolkit applications were developed, it became clear that prompt_toolkit 1.0 was not flexible enough for certain use cases. Mostly, the development of full screen applications was not really natural. All the important components, like the rendering, key bindings, input and output handling were present, but the API was in the first place designed for simple command line prompts. This was mostly notably in the following two places:

  • First, there was the focus which was always pointing to a Buffer (or text input widget), but in full screen applications there are other widgets, like menus and buttons which can be focused.
  • And secondly, it was impossible to make reusable UI components. All the key bindings for the entire applications were stored together in one KeyBindings object, and similar, all Buffer objects were stored together in one dictionary. This didn’t work well. You want reusable components to define their own key bindings and everything. It’s the idea of encapsulation.

For simple prompts, the changes wouldn’t be that invasive, but given that there would be some, I took the opportunity to fix a couple of other things. For instance:

  • In prompt_toolkit 1.0, we translated \r into \n during the input processing. This was not a good idea, because some people wanted to handle these keys individually. This makes sense if you keep in mind that they correspond to Control-M and Control-J. However, we couldn’t fix this without breaking everyone’s enter key, which happens to be the most important key in prompts.

Given that we were going to break compatibility anyway, we changed a couple of other important things that effect both simple prompt applications and full screen applications. These are the most important:

  • We no longer depend on Pygments for styling. While we like Pygments, it was not flexible enough to provide all the styling options that we need, and the Pygments tokens were not ideal for styling anything besides tokenized text.

12 Chapter 3. Table of contents

prompt 𝑡𝑜𝑜𝑙𝑘𝑖𝑡𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛, 𝑅𝑒𝑙𝑒𝑎𝑠𝑒 3. 0. 29

Instead we created something similar to CSS. All UI components can attach classnames to themselves, as well as define an inline style. The final style is then computed by combining the inline styles, the classnames and the style sheet. There are still adaptors available for using Pygments lexers as well as for Pygments styles.

  • The way that key bindings were defined was too complex. KeyBindingsManager was too complex and no longer exists. Every set of key bindings is now a KeyBindings object and multiple of these can be merged together at any time. The runtime performance remains the same, but it’s now easier for users.
  • The separation between the CommandLineInterface and Application class was confusing and in the end, didn’t really had an advantage. These two are now merged together in one Application class.
  • We no longer pass around the active CommandLineInterface. This was one of the most annoying things. Key bindings need it in order to change anything and filters need it in order to evaluate their state. It was pretty annoying, especially because there was usually only one application active at a time. So, Application became a TaskLocal. That is like a global variable, but scoped in the current coroutine or context. The way this works is still not 100% correct, but good enough for the projects that need it (like Pymux), and hopefully Python will get support for this in the future thanks to PEP521, PEP550 or PEP555.

All of these changes have been tested for many months, and I can say with confidence that prompt_toolkit 2.0 is a better prompt_toolkit.

Some new features

Apart from the breaking changes above, there are also some exciting new features.

  • We now support vt100 escape codes for Windows consoles on Windows 10. This means much faster rendering, and full color support.
  • We have a concept of formatted text. This is an object that evaluates to styled text. Every input that expects some text, like the message in a prompt, or the text in a toolbar, can take any kind of formatted text as input. This means you can pass in a plain string, but also a list of (style, text) tuples (similar to a Pygments tokenized string), or an HTML object. This simplifies many APIs.
  • New utilities were added. We now have function for printing formatted text and an experimental module for displaying progress bars.
  • Autocompletion, input validation, and auto suggestion can now either be asynchronous or synchronous. By default they are synchronous, but by wrapping them in ThreadedCompleter, ThreadedValidator or ThreadedAutoSuggest, they will become asynchronous by running in a background thread. Further, if the autocompletion code runs in a background thread, we will show the completions as soon as they arrive. This means that the autocompletion algorithm could for instance first yield the most trivial completions and then take time to produce the completions that take more time.

Upgrading

More guidelines on how to upgrade will follow.

3.3. Upgrading 13

prompt 𝑡𝑜𝑜𝑙𝑘𝑖𝑡𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛, 𝑅𝑒𝑙𝑒𝑎𝑠𝑒 3. 0. 29

Filters

We don’t distiguish anymore between CLIFilter and SimpleFilter , because the application object is no longer passed around. This means that all filters are a Filter from now on.

All filters have been turned into functions. For instance, IsDone became is_done and HasCompletions became has_completions.

This was done because almost all classes were called without any arguments in the init causing additional braces everywhere. This means that HasCompletions() has to be replaced by has_completions (without parenthesis).

The few filters that took arguments as input, became functions, but still have to be called with the given arguments.

For new filters, it is recommended to use the @Condition decorator, rather then inheriting from Filter. For instance:

from prompt_toolkit.filters import Condition

@Condition def my_filter(); return True # Or False

3.3.2 Upgrading to prompt_toolkit 3.

There are two major changes in 3.0 to be aware of:

  • First, prompt_toolkit uses the asyncio event loop natively, rather then using its own implementations of event loops. This means that all coroutines are now asyncio coroutines, and all Futures are asyncio futures. Asyn- chronous generators became real asynchronous generators as well.
  • Prompt_toolkit uses type annotations (almost) everywhere. This should not break any code, but its very helpful in many ways.

There are some minor breaking changes:

  • The dialogs API had to change (see below).

Detecting the prompt_toolkit version

Detecting whether version 3 is being used can be done as follows:

from prompt_toolkit import version as ptk_version

PTK3 = ptk_version.startswith('3.')

Fixing calls to get_event_loop

Every usage of get_event_loop has to be fixed. An easy way to do this is by changing the imports like this:

if PTK3: from asyncio import get_event_loop else: from prompt_toolkit.eventloop import get_event_loop

3.3. Upgrading 15

prompt 𝑡𝑜𝑜𝑙𝑘𝑖𝑡𝐷𝑜𝑐𝑢𝑚𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛, 𝑅𝑒𝑙𝑒𝑎𝑠𝑒 3. 0. 29

Notice that for prompt_toolkit 2.0, get_event_loop returns a prompt_toolkit EventLoop object. This is not an asyncio eventloop, but the API is similar.

There are some changes to the eventloop API:

version 2.0 version 3.0 (asyncio) loop.run_in_executor(callback) loop.run_in_executor(None, callback) loop.call_from_executor(callback) loop.call_soon_threadsafe(callback)

Running on top of asyncio

For 2.0, you had tell prompt_toolkit to run on top of the asyncio event loop. Now it’s the default. So, you can simply remove the following two lines:

from prompt_toolkit.eventloop.defaults import use_asyncio_event_loop use_asyncio_event_loop()

There is a few little breaking changes though. The following:

For 2.

result = await PromptSession().prompt('Say something: ', async_=True)

has to be changed into:

For 3.

result = await PromptSession().prompt_async('Say something: ')

Further, it’s impossible to call the prompt() function within an asyncio application (within a coroutine), because it will try to run the event loop again. In that case, always use prompt_async().

Changes to the dialog functions

The original way of using dialog boxes looked like this:

from prompt_toolkit.shortcuts import input_dialog

result = input_dialog(title='...', text='...')

Now, the dialog functions return a prompt_toolkit Application object. You have to call either its run or run_async method to display the dialog. The async_ parameter has been removed everywhere.

if PTK3: result = input_dialog(title='...', text='...').run() else: result = input_dialog(title='...', text='...')

Or

if PTK3: result = await input_dialog(title='...', text='...').run_async() else: result = await input_dialog(title='...', text='...', async_=True)

16 Chapter 3. Table of contents