Skip to content
Myr

prompts.md

This file

Path

docs/prompts.md

168 lines · 4.5 KiB · Markdown

Last changed by

Move Prompts doc from reST to MyST (#3034)Rowlando13before adoption5b0b7b4

History of this file

Take it

Move Prompts doc from reST to MyST (#3034)Rowlando13before adoption5b0b7b4

lines 1–168why, one step back
1# User Input Prompts
23```{currentmodule} click4```56Click supports prompts in two different places. The first is automated prompts when the parameter handling happens, and7the second is to ask for prompts at a later point independently.89This can be accomplished with the {func}`prompt` function, which asks for valid input according to a type, or the10{func}`confirm` function, which asks for confirmation (yes/no).1112```{contents}13---14depth: 215local: true16---17```1819(option-prompting)=2021## Option Prompts2223Option prompts are integrated into the option interface. Internally, it automatically calls either {func}`prompt` or24{func}`confirm` as necessary.2526In some cases, you want parameters that can be provided from the command line, but if not provided, ask for user input27instead. This can be implemented with Click by defining a prompt string.2829Example:3031```{eval-rst}32.. click:example::3334 @click.command()35 @click.option('--name', prompt=True)36 def hello(name):37 click.echo(f"Hello {name}!")3839And what it looks like:4041.. click:run::4243 invoke(hello, args=['--name=John'])44 invoke(hello, input=['John'])45```4647If you are not happy with the default prompt string, you can ask for48a different one:4950```{eval-rst}51.. click:example::5253 @click.command()54 @click.option('--name', prompt='Your name please')55 def hello(name):56 click.echo(f"Hello {name}!")5758What it looks like:5960.. click:run::6162 invoke(hello, input=['John'])63```6465It is advised that prompt not be used in conjunction with the multiple flag set to True. Instead, prompt in the function66interactively.6768By default, the user will be prompted for an input if one was not passed through the command line. To turn this behavior69off, see {ref}`optional-value`.7071## Input Prompts7273To manually ask for user input, you can use the {func}`prompt` function. By default, it accepts any Unicode string, but74you can ask for any other type. For instance, you can ask for a valid integer:7576```python77value = click.prompt('Please enter a valid integer', type=int)78```7980Additionally, the type will be determined automatically if a default value is provided. For instance, the following will81only accept floats:8283```python84value = click.prompt('Please enter a number', default=42.0)85```8687## Optional Prompts8889If the option has `prompt` enabled, then setting `prompt_required=False` tells Click to only show the prompt if the90option's flag is given, instead of if the option is not provided at all.9192```{eval-rst}93.. click:example::9495 @click.command()96 @click.option('--name', prompt=True, prompt_required=False, default="Default")97 def hello(name):98 click.echo(f"Hello {name}!")99100.. click:run::101102 invoke(hello)103 invoke(hello, args=["--name", "Value"])104 invoke(hello, args=["--name"], input="Prompt")105```106107If `required=True`, then the option will still prompt if it is not given, but it will also prompt if only the flag is108given.109110## Confirmation Prompts111112To ask if a user wants to continue with an action, the {func}`confirm` function comes in handy. By default, it returns113the result of the prompt as a boolean value:114115```python116if click.confirm('Do you want to continue?'):117 click.echo('Well done!')118```119120There is also the option to make the function automatically abort the execution of the program if it does not return121`True`:122123```python124click.confirm('Do you want to continue?', abort=True)125```126127## Dynamic Defaults for Prompts128129The `auto_envvar_prefix` and `default_map` options for the context allow the program to read option values from the130environment or a configuration file. However, this overrides the prompting mechanism, so that the user does not get the131option to change the value interactively.132133If you want to let the user configure the default value, but still be prompted if the option isn't specified on the134command line, you can do so by supplying a callable as the default value. For example, to get a default from the135environment:136137```python138import os139140@click.command()141@click.option(142 "--username", prompt=True,143 default=lambda: os.environ.get("USER", "")144)145def hello(username):146 click.echo(f"Hello, {username}!")147```148149To describe what the default value will be, set it in ``show_default``.150151```{eval-rst}152.. click:example::153154 import os155156 @click.command()157 @click.option(158 "--username", prompt=True,159 default=lambda: os.environ.get("USER", ""),160 show_default="current user"161 )162 def hello(username):163 click.echo(f"Hello, {username}!")164165.. click:run::166167 invoke(hello, args=["--help"])168```