prompt¶
This page documents the param and usage of the prompt()
function.
It’s the entry point for Classic Syntax (PyInquirer).
Synchronous execution¶
- InquirerPy.resolver.prompt(questions, style=None, vi_mode=False, raise_keyboard_interrupt=True, keybindings=None, style_override=True)[source]
Classic syntax entrypoint to create a prompt session.
Resolve user provided list of questions, display prompts and get the results.
- Parameters
questions (Union[List[Dict[str, Any]], Dict[str, Any]]) – A list of question to ask. Refer to documentation for more info.
style (Optional[Dict[str, str]]) – A
dict
containing the style specification for the prompt. Refer to Style for more info.vi_mode (bool) – Use vim keybindings for the prompt instead of the default emacs keybindings. Refer to keybindings for more info.
raise_keyboard_interrupt (bool) – Raise the
KeyboardInterrupt
exception when ctrl-c is pressed. If false, the result will be None and the question is skiped.keybindings (Optional[Dict[str, List[Dict[str, Union[str, FilterOrBool, List[str]]]]]]) – List of custom keybindings to apply. Refer to documentation for more info.
style_override (bool) – Override all default styles. When providing any style customisation, all default styles are removed when this is True.
- Returns
A dictionary containing all of the question answers. The key is the name of the question and the value is the user answer. If the name key is not present as part of the question, then the question index will be used as the key.
- Raises
RequiredKeyNotFound – When the question is missing required keys.
InvalidArgument – When the provided questions argument is not a type of
list
nordictionary
.
- Return type
Dict[Union[str, int], Optional[Union[str, bool, List[Any]]]]
Examples
>>> from InquirerPy import prompt >>> from InquirerPy.validator import NumberValidator >>> questions = [ ... { ... "type": "input", ... "message": "Enter your age:", ... "validate": NumberValidator(), ... "invalid_message": "Input should be number.", ... "default": "18", ... "name": "age", ... "filter": lambda result: int(result), ... "transformer": lambda result: "Adult" if int(result) >= 18 else "Youth", ... }, ... { ... "type": "rawlist", ... "message": "What drinks would you like to buy:", ... "default": 2, ... "choices": lambda result: ["Soda", "Cidr", "Water", "Milk"] ... if result["age"] < 18 ... else ["Wine", "Beer"], ... "name": "drink", ... }, ... { ... "type": "list", ... "message": "Would you like a bag:", ... "choices": ["Yes", "No"], ... "when": lambda result: result["drink"] in {"Wine", "Beer"}, ... }, ... {"type": "confirm", "message": "Confirm?", "default": True}, ... ] >>> result = prompt(questions=questions)
An example using prompt
which incorporate multiple different types of prompts:
from InquirerPy import prompt
from InquirerPy.validator import NumberValidator
questions = [
{
"type": "input",
"message": "Enter your age:",
"validate": NumberValidator(),
"invalid_message": "Input should be number.",
"default": "18",
"name": "age",
"filter": lambda result: int(result),
"transformer": lambda result: "Adult" if int(result) >= 18 else "Youth",
},
{
"type": "rawlist",
"message": "What drinks would you like to buy:",
"default": 2,
"choices": lambda result: ["Soda", "Cidr", "Water", "Milk"]
if result["age"] < 18
else ["Wine", "Beer"],
"name": "drink",
},
{
"type": "list",
"message": "Would you like a bag:",
"choices": ["Yes", "No"],
"when": lambda result: result["drink"] in {"Wine", "Beer"},
},
{"type": "confirm", "message": "Confirm?", "default": True},
]
result = prompt(questions=questions)
questions¶
Union[List[Dict[str, Any]], Dict[str, Any]]
A list
of question to ask.
from InquirerPy import prompt
questions = [
{
"type": "input",
"message": "Enter your name:",
},
{
"type": "Confirm",
"message": "Confirm?",
}
]
result = prompt(questions=questions)
If there’s only one question, you can also just provide a dict
instead of a list
of dict
.
from InquirerPy import prompt
result = prompt(questions={"type": "input", "message": "Enter your name:"})
question¶
Each question is a Python dict
consisting the following keys:
Important
The list below are the common keys that exists across all types of prompt. Checkout the individual prompt documentation for their specific options/parameters.
type (
str
): Type of the prompt.See also
pages/prompts/input:InputPrompt, pages/prompts/secret:SecretPrompt, pages/prompts/filepath:FilePathPrompt, pages/prompts/confirm:ConfirmPrompt, pages/prompts/list:ListPrompt, pages/prompts/rawlist:RawlistPrompt, pages/prompts/expand:ExpandPrompt, pages/prompts/checkbox:CheckboxPrompt, pages/prompts/fuzzy:FuzzyPrompt
name (
Optional[str]
): The key name to use when storing into the result. If not present, the question index within the list of questions will be used as the key name.message (
str, Callable[[Dict[str, Any]], str]
): The question to print. If provided as a function, the current prompt session result will be provided as an argument.default (
Union[Any, Callable[[Dict[str, Any]], Any]]
): Default value to set for the prompt. If provided as a function, the current prompt result will be provided as an argument. Default values can have different meanings across different types of prompt, checkout individual prompt documentation for more info.validate (
Union[Callable[[Any], bool], Validator]
): Check the user answer and return abool
indicating whether the user answer passes the validation or not.See also
invalid_message (
str
): The invalid message to display to the user whenvalidate
failed.See also
filter (
Callable[[Any], Any]
): A function which performs additional transformation on the result. This affects the actual value stored in the final result.transformer (
Callable[[str], Any]
): A function which performs additional transformation on the value that gets printed to the terminal. Different than thefilter
key, this is only visual effect and won’t affect the final result.Tip
filter
andtransformer
key run separately and won’t have side effects when running both.when (
Callable[[SessionResult], bool]
): A function to determine if the question should be asked or skipped. The current prompt session result will be provided as an argument. You can use this key to ask certain questions based on previous question answer conditionally.qmark (
str
): Custom symbol that will be displayed in front of the question message before its answered.amark (
str
): Custom symbol that will be displayed in front of the question message after its answered.instruction (
str
): Short instruction to display next to the question message.wrap_lines (
bool
): Soft wrap question line when question message exceeds the terminal width.mandatory (
bool
): Indicate if the prompt is mandatory. If True, then the question cannot be skipped.mandatory_message (
str
): Error message to show when user attempts to skip mandatory prompt.raise_keyboard_interrupt (
bool
): Raise theKeyboardInterrupt
exception whenctrl-c
is pressed. If false, the result will beNone
and the question is skiped.
Asynchronous execution¶
- async InquirerPy.resolver.prompt_async(questions, style=None, vi_mode=False, raise_keyboard_interrupt=True, keybindings=None, style_override=True)[source]
Classic syntax entrypoint to create a prompt session via asynchronous method.
Refer to
InquirerPy.resolver.prompt()
for detailed documentations.
import asyncio
from InquirerPy import inquirer, prompt_async
async def main():
questions = [
{"type": "input", "message": "Name:"},
{"type": "number", "message": "Number:"},
{"type": "confirm", "message": "Confirm?"},
]
result = await prompt_async(questions)
if __name__ == "__main__":
asyncio.run(main())