Interactive command line user interfaces for Python applications with various prompt types including input, password, lists, checkboxes, and confirmations
npx @tessl/cli install tessl/pypi-pyinquirer@1.0.00
# PyInquirer
1
2
A Python module for creating interactive command line user interfaces based on Inquirer.js. PyInquirer provides a comprehensive set of prompt types for collecting user input with support for validation, filtering, conditional prompts, and custom styling.
3
4
## Package Information
5
6
- **Package Name**: PyInquirer
7
- **Language**: Python
8
- **Installation**: `pip install PyInquirer`
9
- **Dependencies**: `prompt_toolkit==1.0.14`, `Pygments>=2.2.0`, `regex>=2016.11.21`
10
11
## Core Imports
12
13
```python
14
from PyInquirer import prompt, print_json
15
```
16
17
For styling and validation:
18
19
```python
20
from PyInquirer import style_from_dict, Token, Validator, ValidationError, Separator
21
```
22
23
For version information:
24
25
```python
26
from PyInquirer import __version__
27
```
28
29
## Basic Usage
30
31
```python
32
from PyInquirer import prompt, print_json
33
34
questions = [
35
{
36
'type': 'input',
37
'name': 'first_name',
38
'message': 'What\'s your first name?',
39
},
40
{
41
'type': 'confirm',
42
'name': 'continue',
43
'message': 'Do you want to continue?',
44
'default': True
45
},
46
{
47
'type': 'list',
48
'name': 'size',
49
'message': 'What size do you need?',
50
'choices': ['Large', 'Medium', 'Small'],
51
'filter': lambda val: val.lower()
52
}
53
]
54
55
answers = prompt(questions)
56
print_json(answers) # Pretty print the results
57
```
58
59
## Architecture
60
61
PyInquirer follows a question-based approach where prompts are defined as dictionaries with specific properties. The main workflow is:
62
63
1. **Question Definition**: Define questions as dictionaries with type, name, message, and optional properties
64
2. **Prompt Execution**: Pass questions to the `prompt()` function which displays interactive UI
65
3. **Answer Collection**: Receive structured answers dictionary keyed by question names
66
4. **Processing**: Use built-in utilities like `print_json()` for output formatting
67
68
The library supports conditional prompts, validation, filtering, and custom styling through a modular design that separates prompt types, validation logic, and presentation concerns.
69
70
## Capabilities
71
72
### Main Prompt Function
73
74
The core function for displaying interactive prompts to users. All prompt types are accessed through this single function by specifying the `type` parameter in question dictionaries.
75
76
```python { .api }
77
def prompt(questions, answers=None, **kwargs):
78
"""
79
Display interactive prompts to collect user input.
80
81
Parameters:
82
- questions: list or dict, list of question dictionaries or single question
83
- answers: dict, optional existing answers to merge with new responses
84
- patch_stdout: bool, whether to patch stdout (default: False)
85
- return_asyncio_coroutine: bool, return asyncio coroutine (default: False)
86
- true_color: bool, enable true color support (default: False)
87
- refresh_interval: int, refresh interval in milliseconds (default: 0)
88
- eventloop: custom event loop (default: None)
89
- keyboard_interrupt_msg: str, message on Ctrl+C (default: 'Cancelled by user')
90
91
Returns:
92
dict: Dictionary of answers keyed by question names
93
"""
94
```
95
96
### Input Prompts
97
98
Basic text input with optional validation and filtering. Supports default values, custom validation functions, and input processing.
99
100
```python { .api }
101
# Question format for input prompts
102
{
103
'type': 'input',
104
'name': str, # Key for storing answer
105
'message': str, # Question text to display
106
'default': str, # Default value (optional)
107
'validate': callable, # Validation function or Validator class (optional)
108
'filter': callable, # Function to process the answer (optional)
109
'when': callable, # Function to conditionally show question (optional)
110
'qmark': str, # Custom question mark symbol (default: '?') (optional)
111
'style': object # Custom style object (default: default_style) (optional)
112
}
113
```
114
115
Usage example:
116
117
```python
118
questions = [
119
{
120
'type': 'input',
121
'name': 'phone',
122
'message': 'What\'s your phone number?',
123
'validate': lambda val: len(val) >= 10 or 'Phone number must be at least 10 digits'
124
}
125
]
126
```
127
128
**Key bindings:**
129
- `Text input`: Type characters normally
130
- `Enter`: Submit input (if validation passes)
131
- `Ctrl+C`: Cancel and exit
132
- `←/→` (Arrow keys): Move cursor within input
133
- `Backspace/Delete`: Delete characters
134
135
### Password Prompts
136
137
Masked password input that extends input prompts with hidden character display.
138
139
```python { .api }
140
# Question format for password prompts
141
{
142
'type': 'password',
143
'name': str, # Key for storing answer
144
'message': str, # Question text to display
145
'default': str, # Default value (optional)
146
'validate': callable, # Validation function (optional)
147
'filter': callable, # Function to process answer (optional)
148
'when': callable, # Conditional display function (optional)
149
'qmark': str, # Custom question mark symbol (default: '?') (optional)
150
'style': object # Custom style object (default: default_style) (optional)
151
}
152
```
153
154
**Key bindings:**
155
- `Text input`: Type characters (displayed as masked)
156
- `Enter`: Submit password (if validation passes)
157
- `Ctrl+C`: Cancel and exit
158
- `←/→` (Arrow keys): Move cursor within input
159
- `Backspace/Delete`: Delete characters
160
161
### Confirmation Prompts
162
163
Yes/No confirmation prompts with customizable default values.
164
165
```python { .api }
166
# Question format for confirm prompts
167
{
168
'type': 'confirm',
169
'name': str, # Key for storing answer
170
'message': str, # Question text to display
171
'default': bool, # Default value (True or False, optional)
172
'when': callable, # Conditional display function (optional)
173
'qmark': str, # Custom question mark symbol (default: '?') (optional)
174
'style': object # Custom style object (default: default_style) (optional)
175
}
176
```
177
178
**Key bindings:**
179
- `y/Y`: Select Yes
180
- `n/N`: Select No
181
- `Enter`: Use default value (if set)
182
- `Ctrl+C`: Cancel and exit
183
184
### List Selection Prompts
185
186
Single-choice selection from a list with arrow key navigation.
187
188
```python { .api }
189
# Question format for list prompts
190
{
191
'type': 'list',
192
'name': str, # Key for storing answer
193
'message': str, # Question text to display
194
'choices': list, # List of choice strings or choice objects
195
'default': any, # Default choice index or value (optional)
196
'filter': callable, # Function to process selected value (optional)
197
'when': callable, # Conditional display function (optional)
198
'qmark': str, # Custom question mark symbol (default: '?') (optional)
199
'style': object, # Custom style object (default: default_style) (optional)
200
'pageSize': int # Number of choices to display per page (optional)
201
}
202
203
# Choice object format
204
{
205
'name': str, # Display name
206
'value': any, # Actual value (defaults to name if not specified)
207
'disabled': bool or str # Disable choice with optional reason text
208
}
209
```
210
211
**Key bindings:**
212
- `↑/↓` (Arrow keys): Navigate up/down through choices
213
- `Enter`: Select current choice
214
- `Ctrl+C`: Cancel and exit
215
- Mouse click: Direct selection (if supported)
216
217
### Raw List Prompts
218
219
Numbered list selection where users type the number corresponding to their choice.
220
221
```python { .api }
222
# Question format for rawlist prompts
223
{
224
'type': 'rawlist',
225
'name': str, # Key for storing answer
226
'message': str, # Question text to display
227
'choices': list, # List of choice strings or choice objects
228
'default': int, # Default choice index (optional)
229
'filter': callable, # Function to process selected value (optional)
230
'when': callable, # Conditional display function (optional)
231
'qmark': str, # Custom question mark symbol (default: '?') (optional)
232
'style': object # Custom style object (default: default_style) (optional)
233
}
234
```
235
236
**Key bindings:**
237
- `1-9` (Number keys): Select choice by number (max 9 choices)
238
- `Enter`: Confirm selection
239
- `Ctrl+C`: Cancel and exit
240
241
**Limitations:**
242
- Maximum 9 choices supported
243
- Choice indexes start at 1, not 0
244
245
### Checkbox Prompts
246
247
Multiple choice selection with spacebar to toggle individual options.
248
249
```python { .api }
250
# Question format for checkbox prompts
251
{
252
'type': 'checkbox',
253
'name': str, # Key for storing answer
254
'message': str, # Question text to display
255
'choices': list, # List of choice strings or choice objects
256
'default': list, # List of default selected values (optional)
257
'validate': callable, # Validation function for selected items (optional)
258
'filter': callable, # Function to process selected values (optional)
259
'when': callable, # Conditional display function (optional)
260
'qmark': str, # Custom question mark symbol (default: '?') (optional)
261
'style': object # Custom style object (default: default_style) (optional)
262
}
263
264
# Choice object format with checkbox-specific properties
265
{
266
'name': str, # Display name
267
'value': any, # Actual value (defaults to name)
268
'checked': bool, # Pre-select this choice (default: False)
269
'disabled': bool or str # Disable choice with optional reason text
270
}
271
```
272
273
**Key bindings:**
274
- `↑/↓` (Arrow keys): Navigate up/down through choices
275
- `Space`: Toggle selection of current choice
276
- `a`: Toggle all (select all/deselect all)
277
- `i`: Invert selection (selected becomes unselected and vice versa)
278
- `Enter`: Confirm final selection
279
- `Ctrl+C`: Cancel and exit
280
- Mouse click: Toggle individual choice
281
282
### Expand Prompts
283
284
Compact single-choice prompt that expands to show all options. Users type single-character shortcuts to select options.
285
286
```python { .api }
287
# Question format for expand prompts
288
{
289
'type': 'expand',
290
'name': str, # Key for storing answer
291
'message': str, # Question text to display
292
'choices': list, # List of choice objects with key shortcuts
293
'default': str, # Default choice key (defaults to 'h' for help)
294
'when': callable, # Conditional display function (optional)
295
'qmark': str, # Custom question mark symbol (default: '?') (optional)
296
'style': object # Custom style object (default: default_style) (optional)
297
}
298
299
# Choice object format for expand prompts
300
{
301
'key': str, # Single character shortcut (lowercase)
302
'name': str, # Display name and description
303
'value': any # Actual value to return
304
}
305
```
306
307
**Key bindings:**
308
- `<letter>` (Choice key): Select choice by typing its key letter
309
- `h`: Show help (expand all options)
310
- `Enter`: Confirm current selection
311
- `Ctrl+C`: Cancel and exit
312
313
Usage example:
314
315
```python
316
{
317
'type': 'expand',
318
'name': 'conflict',
319
'message': 'Conflict on file.js:',
320
'choices': [
321
{'key': 'y', 'name': 'Overwrite', 'value': 'overwrite'},
322
{'key': 'a', 'name': 'Overwrite this one and all next', 'value': 'overwrite_all'},
323
{'key': 'd', 'name': 'Show diff', 'value': 'diff'}
324
]
325
}
326
```
327
328
### Editor Prompts
329
330
Opens external editor for multi-line text input. Supports various editors and configuration options.
331
332
```python { .api }
333
# Question format for editor prompts
334
{
335
'type': 'editor',
336
'name': str, # Key for storing answer
337
'message': str, # Question text to display
338
'default': str, # Default text to edit (optional)
339
'validate': callable, # Validation function (optional)
340
'filter': callable, # Function to process answer (optional)
341
'eargs': dict, # Editor configuration (optional)
342
'when': callable, # Conditional display function (optional)
343
'qmark': str, # Custom question mark symbol (default: '?') (optional)
344
'style': object # Custom style object (default: default_style) (optional)
345
}
346
347
# Editor arguments (eargs) format
348
{
349
'editor': str, # Editor command/path (optional, default detected from environment)
350
'env': dict, # Environment variables (optional)
351
'ext': str, # File extension for temp file (optional, default: '.txt')
352
'save': bool, # Whether to save file (optional, default: True)
353
'filename': str # Edit existing file instead of temp file (optional)
354
}
355
```
356
357
### Utility Functions
358
359
Helper functions for output formatting and data processing.
360
361
```python { .api }
362
def print_json(data):
363
"""
364
Pretty print JSON data with syntax highlighting.
365
366
Parameters:
367
- data: any, data to format and print as JSON
368
"""
369
370
def format_json(data):
371
"""
372
Format data as indented JSON string.
373
374
Parameters:
375
- data: any, data to format
376
377
Returns:
378
str: Formatted JSON string
379
"""
380
381
def colorize_json(data):
382
"""
383
Add syntax highlighting to JSON data.
384
385
Parameters:
386
- data: any, data to colorize
387
388
Returns:
389
str: JSON string with ANSI color codes
390
"""
391
392
def here(path):
393
"""
394
Get absolute path relative to package directory.
395
396
Parameters:
397
- path: str, relative path from package root
398
399
Returns:
400
str: Absolute path
401
"""
402
403
def yellow(message):
404
"""
405
Print message in yellow color.
406
407
Parameters:
408
- message: str, text to print in yellow
409
"""
410
411
def blue(message):
412
"""
413
Print message in blue color.
414
415
Parameters:
416
- message: str, text to print in blue
417
"""
418
419
def gray(message):
420
"""
421
Print message in gray color.
422
423
Parameters:
424
- message: str, text to print in gray
425
"""
426
427
# Package version constant
428
__version__: str # Package version string (e.g., '1.0.2')
429
```
430
431
432
### Separator Class
433
434
Visual separator for grouping choices in list-based prompts.
435
436
```python { .api }
437
class Separator:
438
"""
439
Visual separator for choice groups.
440
441
Parameters:
442
- line: str, custom separator line (default: 15 dashes)
443
"""
444
445
def __init__(self, line=None):
446
"""
447
Create separator with optional custom line.
448
449
Parameters:
450
- line: str, separator line text (optional)
451
"""
452
453
def __str__(self):
454
"""
455
Returns:
456
str: The separator line string
457
"""
458
```
459
460
Usage example:
461
462
```python
463
from PyInquirer import Separator
464
465
choices = [
466
'Option 1',
467
'Option 2',
468
Separator(),
469
'Option 3',
470
'Option 4',
471
Separator('= Advanced Options ='),
472
'Advanced Option 1'
473
]
474
```
475
476
### Validation Classes
477
478
Input validation support with custom validators and error handling.
479
480
```python { .api }
481
class Validator:
482
"""
483
Base class for input validators.
484
Re-exported from prompt_toolkit.validation.
485
"""
486
487
def validate(self, document):
488
"""
489
Validate input document.
490
491
Parameters:
492
- document: Document object with text property
493
494
Raises:
495
ValidationError: If validation fails
496
"""
497
498
class ValidationError(Exception):
499
"""
500
Exception raised for validation failures.
501
Re-exported from prompt_toolkit.validation.
502
503
Parameters:
504
- message: str, error message to display
505
- cursor_position: int, cursor position for error highlight (optional)
506
"""
507
```
508
509
Custom validator example:
510
511
```python
512
from PyInquirer import Validator, ValidationError
513
514
class NumberValidator(Validator):
515
def validate(self, document):
516
try:
517
int(document.text)
518
except ValueError:
519
raise ValidationError(
520
message='Please enter a valid number',
521
cursor_position=len(document.text)
522
)
523
```
524
525
### Styling System
526
527
Customizable styling for prompts using token-based theming.
528
529
```python { .api }
530
def style_from_dict(style_dict):
531
"""
532
Create style from dictionary of token mappings.
533
Re-exported from prompt_toolkit.styles.
534
535
Parameters:
536
- style_dict: dict, mapping of Token types to color/style strings
537
538
Returns:
539
Style object for use with prompts
540
"""
541
542
# Available style tokens
543
class Token:
544
"""
545
Style token types for customizing prompt appearance.
546
Re-exported from prompt_toolkit.token.
547
"""
548
Separator = None # Separator line color
549
QuestionMark = None # Question mark (?) color
550
Selected = None # Selected item color
551
Pointer = None # Arrow pointer color
552
Instruction = None # Instruction text color
553
Answer = None # Answer text color
554
Question = None # Question text color
555
SetCursorPosition = None # Cursor positioning token
556
557
# Default style object
558
default_style: object # Default orange-themed style with mappings:
559
# Token.Separator: '#6C6C6C'
560
# Token.QuestionMark: '#5F819D'
561
# Token.Selected: ''
562
# Token.Pointer: '#FF9D00 bold'
563
# Token.Instruction: ''
564
# Token.Answer: '#FF9D00 bold'
565
# Token.Question: 'bold'
566
```
567
568
Custom styling example:
569
570
```python
571
from PyInquirer import style_from_dict, Token, prompt
572
573
custom_style = style_from_dict({
574
Token.QuestionMark: '#E91E63 bold',
575
Token.Selected: '#673AB7 bold',
576
Token.Answer: '#2196f3 bold',
577
Token.Question: 'bold',
578
})
579
580
answers = prompt(questions, style=custom_style)
581
```
582
583
### Exception Classes
584
585
Custom exceptions for error handling and parameter validation.
586
587
```python { .api }
588
class PromptParameterException(ValueError):
589
"""
590
Exception raised when required prompt parameters are missing.
591
592
Parameters:
593
- message: str, name of missing parameter
594
- errors: any, additional error information (optional)
595
"""
596
597
def __init__(self, message, errors=None):
598
"""
599
Create exception for missing parameter.
600
601
Parameters:
602
- message: str, parameter name that is missing
603
- errors: any, additional error context (optional)
604
"""
605
606
class EditorArgumentsError(Exception):
607
"""
608
Exception raised for invalid editor configuration arguments.
609
Used specifically by editor prompts when eargs parameters are invalid.
610
"""
611
```
612
613
## Common Patterns
614
615
### Conditional Prompts
616
617
```python
618
questions = [
619
{
620
'type': 'confirm',
621
'name': 'has_comments',
622
'message': 'Do you have any comments?'
623
},
624
{
625
'type': 'input',
626
'name': 'comments',
627
'message': 'Please enter your comments:',
628
'when': lambda answers: answers.get('has_comments', False)
629
}
630
]
631
```
632
633
### Dynamic Choices
634
635
```python
636
def get_size_choices(answers):
637
if answers.get('category') == 'clothing':
638
return ['XS', 'S', 'M', 'L', 'XL']
639
else:
640
return ['Small', 'Medium', 'Large']
641
642
questions = [
643
{
644
'type': 'list',
645
'name': 'category',
646
'message': 'Select category:',
647
'choices': ['clothing', 'electronics']
648
},
649
{
650
'type': 'list',
651
'name': 'size',
652
'message': 'Select size:',
653
'choices': get_size_choices
654
}
655
]
656
```
657
658
### Input Validation and Filtering
659
660
```python
661
questions = [
662
{
663
'type': 'input',
664
'name': 'quantity',
665
'message': 'How many items?',
666
'validate': lambda val: val.isdigit() or 'Please enter a valid number',
667
'filter': lambda val: int(val) # Convert string to integer
668
}
669
]
670
```