0
# User Prompts and Input
1
2
Interactive user prompts with validation support for creating CLI applications that require user input. The prompt module provides yes/no questions, text input with validation, and multiple choice options with built-in batch mode support for automated testing.
3
4
## Capabilities
5
6
### Yes/No Prompts
7
8
Simple yes/no prompts with configurable defaults and batch mode support for automated testing.
9
10
```python { .api }
11
def yn(prompt, default='y', batch=False):
12
"""
13
Display a yes/no prompt to the user.
14
15
Args:
16
prompt (str): The question to ask the user
17
default (str): Default choice ('y' or 'n'), defaults to 'y'
18
batch (bool): If True, automatically returns default without user input
19
20
Returns:
21
bool: True if user confirms, False otherwise
22
"""
23
```
24
25
**Usage Example:**
26
27
```python
28
from clint.textui import prompt
29
30
# Basic yes/no prompt
31
if prompt.yn('Do you want to continue?'):
32
print('Continuing...')
33
34
# With custom default
35
result = prompt.yn('Delete all files?', default='n')
36
37
# Batch mode (for automated scripts)
38
result = prompt.yn('Proceed?', batch=True) # Uses default
39
```
40
41
### Text Input Queries
42
43
General text input prompts with validation support, default values, and batch mode capability.
44
45
```python { .api }
46
def query(prompt, default='', validators=None, batch=False):
47
"""
48
Prompt user for text input with validation.
49
50
Args:
51
prompt (str): The input prompt to display
52
default (str): Default value if user provides no input
53
validators (list): List of validator objects to validate input
54
batch (bool): If True, automatically returns default without user input
55
56
Returns:
57
str: Validated user input or default value
58
"""
59
```
60
61
**Usage Example:**
62
63
```python
64
from clint.textui import prompt
65
from clint.textui.validators import RegexValidator, IntegerValidator
66
67
# Simple text input
68
name = prompt.query('Enter your name:')
69
70
# With default value
71
email = prompt.query('Email address:', default='user@example.com')
72
73
# With validation
74
age = prompt.query('Enter age:', validators=[IntegerValidator()])
75
76
# Email validation
77
email = prompt.query('Email:', validators=[
78
RegexValidator(r'^[^@]+@[^@]+\.[^@]+$', 'Enter a valid email')
79
])
80
81
# Batch mode
82
name = prompt.query('Name:', default='Anonymous', batch=True)
83
```
84
85
### Multiple Choice Options
86
87
Multiple choice prompts supporting both simple lists and complex option dictionaries with custom selectors and return values.
88
89
```python { .api }
90
def options(prompt, options, default=None, batch=False):
91
"""
92
Display multiple choice options to the user.
93
94
Args:
95
prompt (str): The question to ask the user
96
options (list): List of strings or dictionaries defining options
97
default (str): Default selector value
98
batch (bool): If True, automatically returns default without user input
99
100
Returns:
101
Various: Selected option value (depends on option configuration)
102
"""
103
```
104
105
**Option Formats:**
106
107
```python { .api }
108
# Simple string list format
109
options = ['Option 1', 'Option 2', 'Option 3']
110
111
# Dictionary format for advanced control
112
options = [
113
{
114
'selector': '1', # What user types to select
115
'prompt': 'First option', # Display text (optional)
116
'return': 'value1' # Return value (optional)
117
},
118
{
119
'selector': 'a',
120
'prompt': 'Alternative option',
121
'return': {'key': 'value'}
122
}
123
]
124
```
125
126
**Usage Examples:**
127
128
```python
129
from clint.textui import prompt
130
131
# Simple string options (automatically numbered)
132
choice = prompt.options('Choose a color:', ['Red', 'Green', 'Blue'])
133
# Displays: [1] Red, [2] Green, [3] Blue
134
# Returns: 1, 2, or 3
135
136
# Custom dictionary options
137
choice = prompt.options('Select environment:', [
138
{'selector': 'dev', 'prompt': 'Development', 'return': 'development'},
139
{'selector': 'prod', 'prompt': 'Production', 'return': 'production'},
140
{'selector': 'test', 'prompt': 'Testing', 'return': 'testing'}
141
])
142
# User types 'dev', function returns 'development'
143
144
# With default
145
choice = prompt.options('Environment:',
146
['Development', 'Production'],
147
default='1'
148
)
149
150
# Batch mode
151
choice = prompt.options('Select:', ['A', 'B'], default='1', batch=True)
152
```
153
154
## Integration with Validators
155
156
All prompt functions integrate with the validation system from `clint.textui.validators`:
157
158
```python
159
from clint.textui import prompt
160
from clint.textui.validators import RegexValidator, PathValidator, IntegerValidator
161
162
# Multiple validators
163
port = prompt.query('Port number:', validators=[
164
IntegerValidator('Must be a number'),
165
RegexValidator(r'^[1-9]\d{3,4}$', 'Must be 1000-65535')
166
])
167
168
# Path validation
169
config_path = prompt.query('Config file:', validators=[
170
PathValidator('Directory must exist')
171
])
172
```
173
174
## Error Handling
175
176
When validation fails, prompts display error messages in yellow and repeat the question:
177
178
```python
179
# If user enters invalid input, they see:
180
# Enter a valid number.
181
# Port number: [prompt repeats]
182
```
183
184
## Batch Mode
185
186
Batch mode is designed for automated scripts and testing:
187
188
```python
189
# In batch mode, prompts display but don't wait for input
190
result = prompt.yn('Continue?', batch=True) # Uses default
191
name = prompt.query('Name:', default='Test', batch=True) # Returns 'Test'
192
choice = prompt.options('Pick:', ['A', 'B'], default='1', batch=True) # Returns 1
193
```