Search code examples
python-3.xconsole-applicationprompt-toolkit

python propmpt-toolkit simple input coloring


I am trying to write a console application for some database entry that would run in terminal. After considering several CLI libraries, I have selected prompt-toolkit as closest to my needs (cli frameworks are overly concentrated towards command line tools). Prompt-toolkit documentation is moderately large, but in many cases fails to document simple use cases and quickly jumps to advanced topics.

Consider following code:

from prompt_toolkit import prompt, PromptSession, print_formatted_text, HTML
pts = PromptSession()
result = pts.prompt(HTML('<b>Enter some data > </b>'))

When run this shows:

Enter some data > User types input here

As you may notice the prompt is 'bold' (using HTML for coloring prompt is hardly documented, but I figured it is working). What I am failing to figure out is coloring of user input part - in other words I would like to color "User types input here" in some simple way (some color or effect that would make user input stand out) without using some lexer method (which is extensively documented) as I am not entering some sort of code but some simple data.

It is mentioned that it is possible to use style= argument for this but when I try enter 'format string' I get error (code goes something like this):

result = pts.prompt(HTML('<b>Enter some data > </b>'), style="fg:ansiyellow bg:black bold underline")

according to https://python-prompt-toolkit.readthedocs.io/en/stable/pages/advanced_topics/styling.html#styling this shall be acceptable styling for inputs (as far as I understand).

Any hints where to look?


Solution

  • I have personally used something like the below in my code. Granted it is a bit hacky, but style= is applied to the entire prompt, hence needing to override that by using a HTML formatted string.

    prompt(HTML("<ansigray>Please enter text: </ansigray>"), style=Style.from_dict({'': 'ansired'}))
    

    Which will generate output as:

    Please enter text: Hello
    

    Where "Please enter text" will be in ansigray, the default terminal text color, and "Hello", the user input, will be red color

    Regarding the style= argument, it needs to be instantiated as a Style object with a dictionary of rules.

    I found the examples here decently handy: https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/examples/prompts/colored-prompt.py

    Same goes for the documentation, which has various examples (albeit not for this exact scenario): https://python-prompt-toolkit.readthedocs.io/en/master/pages/asking_for_input.html#colors

    And finally ansi colors and the style rules are documented here: https://python-prompt-toolkit.readthedocs.io/en/master/pages/advanced_topics/styling.html