0
# Terminal Utilities
1
2
Re-exported Click functions for terminal interaction, styling, and user input/output operations. These utilities provide cross-platform terminal functionality for CLI applications.
3
4
## Capabilities
5
6
### Output Functions
7
8
Functions for displaying text and information to the terminal with various formatting options.
9
10
```python { .api }
11
def echo(message: Optional[str] = None, file=None, nl: bool = True, err: bool = False, color: Optional[bool] = None):
12
"""
13
Print a message to stdout or stderr.
14
15
Parameters:
16
- message: Text to print
17
- file: File object to write to (default: stdout)
18
- nl: Add newline at the end
19
- err: Write to stderr instead of stdout
20
- color: Force enable/disable colors
21
22
Example:
23
```python
24
typer.echo("Hello World!")
25
typer.echo("Error occurred", err=True)
26
```
27
"""
28
29
def secho(message: Optional[str] = None, file=None, nl: bool = True, err: bool = False, color: Optional[bool] = None, **styles):
30
"""
31
Print a styled message to stdout or stderr.
32
33
Parameters:
34
- message: Text to print
35
- file: File object to write to
36
- nl: Add newline at the end
37
- err: Write to stderr instead of stdout
38
- color: Force enable/disable colors
39
- styles: Style keywords (fg, bg, bold, dim, underline, blink, reverse, reset)
40
41
Example:
42
```python
43
typer.secho("Success!", fg="green", bold=True)
44
typer.secho("Warning!", fg="yellow")
45
typer.secho("Error!", fg="red", err=True)
46
```
47
"""
48
49
def style(text: str, fg=None, bg=None, bold: Optional[bool] = None, dim: Optional[bool] = None, underline: Optional[bool] = None, blink: Optional[bool] = None, reverse: Optional[bool] = None, reset: bool = True) -> str:
50
"""
51
Apply styling to text and return styled string.
52
53
Parameters:
54
- text: Text to style
55
- fg: Foreground color
56
- bg: Background color
57
- bold: Bold text
58
- dim: Dim text
59
- underline: Underlined text
60
- blink: Blinking text
61
- reverse: Reverse video
62
- reset: Reset styles after text
63
64
Returns:
65
Styled text string
66
67
Example:
68
```python
69
styled = typer.style("Important", fg="red", bold=True)
70
typer.echo(styled)
71
```
72
"""
73
74
def unstyle(text: str) -> str:
75
"""
76
Remove all ANSI styling from text.
77
78
Parameters:
79
- text: Text with ANSI codes
80
81
Returns:
82
Plain text without styling
83
84
Example:
85
```python
86
plain = typer.unstyle("\x1b[31mRed text\x1b[0m")
87
# plain == "Red text"
88
```
89
"""
90
```
91
92
### User Input Functions
93
94
Functions for prompting users for input with various validation and formatting options.
95
96
```python { .api }
97
def prompt(text: str, default=None, hide_input: bool = False, confirmation_prompt: bool = False, type=None, value_proc=None, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False, show_choices: bool = True) -> Any:
98
"""
99
Prompt user for input.
100
101
Parameters:
102
- text: Prompt text to display
103
- default: Default value if user enters nothing
104
- hide_input: Hide input (for passwords)
105
- confirmation_prompt: Ask for confirmation
106
- type: Input type (int, float, etc.)
107
- value_proc: Function to process the value
108
- prompt_suffix: Suffix after prompt text
109
- show_default: Show default value in prompt
110
- err: Show prompt on stderr
111
- show_choices: Show available choices
112
113
Returns:
114
User input value
115
116
Example:
117
```python
118
name = typer.prompt("Your name")
119
age = typer.prompt("Your age", type=int)
120
password = typer.prompt("Password", hide_input=True)
121
```
122
"""
123
124
def confirm(text: str, default: bool = False, abort: bool = False, prompt_suffix: str = " [y/N]: ", show_default: bool = True, err: bool = False) -> bool:
125
"""
126
Prompt user for yes/no confirmation.
127
128
Parameters:
129
- text: Confirmation text
130
- default: Default value (True/False)
131
- abort: Raise Abort exception if user says no
132
- prompt_suffix: Suffix for the prompt
133
- show_default: Show default in prompt
134
- err: Show prompt on stderr
135
136
Returns:
137
True if user confirms, False otherwise
138
139
Example:
140
```python
141
if typer.confirm("Delete all files?"):
142
typer.echo("Deleting files...")
143
else:
144
typer.echo("Aborted.")
145
```
146
"""
147
```
148
149
### Terminal Control Functions
150
151
Functions for controlling terminal display and behavior.
152
153
```python { .api }
154
def clear():
155
"""
156
Clear the terminal screen.
157
158
Example:
159
```python
160
typer.clear()
161
typer.echo("Screen cleared!")
162
```
163
"""
164
165
def pause(info: str = "Press any key to continue..."):
166
"""
167
Pause execution until user presses a key.
168
169
Parameters:
170
- info: Message to display
171
172
Example:
173
```python
174
typer.echo("Processing complete.")
175
typer.pause()
176
typer.echo("Continuing...")
177
```
178
"""
179
180
def getchar(echo: bool = False) -> str:
181
"""
182
Get a single character from stdin.
183
184
Parameters:
185
- echo: Echo the character to stdout
186
187
Returns:
188
Single character string
189
190
Example:
191
```python
192
typer.echo("Press any key...")
193
char = typer.getchar()
194
typer.echo(f"You pressed: {char}")
195
```
196
"""
197
```
198
199
### Advanced Output Functions
200
201
Functions for handling large amounts of text and complex output scenarios.
202
203
```python { .api }
204
def echo_via_pager(text_or_generator, color: Optional[bool] = None):
205
"""
206
Echo text through a pager (like 'less' or 'more').
207
208
Parameters:
209
- text_or_generator: Text string or generator yielding text
210
- color: Enable/disable colors in pager
211
212
Example:
213
```python
214
long_text = "\\n".join(f"Line {i}" for i in range(1000))
215
typer.echo_via_pager(long_text)
216
```
217
"""
218
219
def edit(text: Optional[str] = None, editor: Optional[str] = None, env: Optional[str] = None, require_save: bool = True, extension: str = ".txt", filename: Optional[str] = None) -> Optional[str]:
220
"""
221
Open text editor for user input.
222
223
Parameters:
224
- text: Initial text content
225
- editor: Editor command to use
226
- env: Environment variable for editor
227
- require_save: Require user to save
228
- extension: File extension for temp file
229
- filename: Specific filename to use
230
231
Returns:
232
Edited text or None if not saved
233
234
Example:
235
```python
236
edited_text = typer.edit("Initial content")
237
if edited_text:
238
typer.echo("Text was edited")
239
```
240
"""
241
242
def progressbar(iterable=None, length: Optional[int] = None, label: Optional[str] = None, show_eta: bool = True, show_percent: Optional[bool] = None, show_pos: bool = False, item_show_func=None, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s [%(bar)s] %(info)s", info_sep: str = " ", width: int = 36, file=None, color: Optional[bool] = None):
243
"""
244
Create a progress bar for iterating over items.
245
246
Parameters:
247
- iterable: Items to iterate over
248
- length: Total number of items (if iterable doesn't have len())
249
- label: Label to show before progress bar
250
- show_eta: Show estimated time remaining
251
- show_percent: Show percentage complete
252
- show_pos: Show current position
253
- item_show_func: Function to display current item
254
- fill_char: Character for completed portion
255
- empty_char: Character for remaining portion
256
- bar_template: Template for bar display
257
- info_sep: Separator for info sections
258
- width: Width of progress bar
259
- file: File to write progress to
260
- color: Enable/disable colors
261
262
Returns:
263
Progress bar context manager
264
265
Example:
266
```python
267
import time
268
269
items = range(100)
270
with typer.progressbar(items, label="Processing") as progress:
271
for item in progress:
272
time.sleep(0.01) # Simulate work
273
```
274
"""
275
```
276
277
### File and System Utilities
278
279
Utility functions for file operations and system interaction.
280
281
```python { .api }
282
def format_filename(filename: str, shorten: bool = False) -> str:
283
"""
284
Format a filename for display.
285
286
Parameters:
287
- filename: Filename to format
288
- shorten: Shorten long filenames
289
290
Returns:
291
Formatted filename string
292
293
Example:
294
```python
295
formatted = typer.format_filename("/very/long/path/to/file.txt", shorten=True)
296
typer.echo(f"Processing {formatted}")
297
```
298
"""
299
300
def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:
301
"""
302
Get the application directory for storing data.
303
304
Parameters:
305
- app_name: Name of the application
306
- roaming: Use roaming directory on Windows
307
- force_posix: Force POSIX-style paths
308
309
Returns:
310
Application directory path
311
312
Example:
313
```python
314
app_dir = typer.get_app_dir("myapp")
315
config_file = os.path.join(app_dir, "config.json")
316
```
317
"""
318
319
def get_binary_stream(name: str):
320
"""
321
Get a binary stream (stdin/stdout/stderr).
322
323
Parameters:
324
- name: Stream name ("stdin", "stdout", "stderr")
325
326
Returns:
327
Binary stream object
328
329
Example:
330
```python
331
stdin = typer.get_binary_stream("stdin")
332
data = stdin.read()
333
```
334
"""
335
336
def get_text_stream(name: str, encoding: Optional[str] = None, errors: str = "strict"):
337
"""
338
Get a text stream (stdin/stdout/stderr).
339
340
Parameters:
341
- name: Stream name ("stdin", "stdout", "stderr")
342
- encoding: Text encoding
343
- errors: Error handling
344
345
Returns:
346
Text stream object
347
348
Example:
349
```python
350
stdout = typer.get_text_stream("stdout")
351
stdout.write("Hello World!")
352
```
353
"""
354
355
def open_file(filename: str, mode: str = "r", encoding: Optional[str] = None, errors: str = "strict", lazy: bool = False, atomic: bool = False):
356
"""
357
Open a file with proper error handling and atomic operations.
358
359
Parameters:
360
- filename: Name of file to open
361
- mode: File open mode
362
- encoding: Text encoding
363
- errors: Error handling
364
- lazy: Lazy file opening
365
- atomic: Atomic file operations
366
367
Returns:
368
File object
369
370
Example:
371
```python
372
with typer.open_file("data.txt", "w", atomic=True) as f:
373
f.write("Safe atomic write")
374
```
375
"""
376
377
def get_terminal_size() -> os.terminal_size:
378
"""
379
Get the terminal size.
380
381
Returns:
382
Terminal size with columns and lines attributes
383
384
Example:
385
```python
386
size = typer.get_terminal_size()
387
typer.echo(f"Terminal: {size.columns}x{size.lines}")
388
```
389
"""
390
```
391
392
## Usage Examples
393
394
### Styled Output
395
396
```python
397
import typer
398
399
def show_status():
400
"""Demonstrate styled output."""
401
typer.secho("✓ Success", fg="green", bold=True)
402
typer.secho("⚠ Warning", fg="yellow")
403
typer.secho("✗ Error", fg="red", err=True)
404
405
# Custom styling
406
styled_text = typer.style("Important Info", fg="blue", underline=True)
407
typer.echo(f"Note: {styled_text}")
408
409
if __name__ == "__main__":
410
typer.run(show_status)
411
```
412
413
### Interactive Input
414
415
```python
416
import typer
417
418
def interactive_setup():
419
"""Interactive application setup."""
420
typer.echo("Welcome to App Setup!")
421
422
name = typer.prompt("Your name")
423
age = typer.prompt("Your age", type=int, default=25)
424
email = typer.prompt("Email address")
425
426
password = typer.prompt("Password", hide_input=True, confirmation_prompt=True)
427
428
typer.echo(f"\\nHello {name}! You are {age} years old.")
429
typer.echo(f"Email: {email}")
430
431
if typer.confirm("Save configuration?"):
432
typer.secho("Configuration saved!", fg="green")
433
else:
434
typer.secho("Configuration discarded.", fg="yellow")
435
436
if __name__ == "__main__":
437
typer.run(interactive_setup)
438
```
439
440
### Progress Bar
441
442
```python
443
import typer
444
import time
445
446
def process_items():
447
"""Demonstrate progress bar usage."""
448
items = list(range(50))
449
450
with typer.progressbar(items, label="Processing items") as progress:
451
for item in progress:
452
# Simulate processing time
453
time.sleep(0.1)
454
455
typer.secho("All items processed!", fg="green")
456
457
if __name__ == "__main__":
458
typer.run(process_items)
459
```
460
461
### File Operations
462
463
```python
464
import typer
465
from pathlib import Path
466
467
def safe_file_write(
468
content: str,
469
filename: str = typer.Option("output.txt", help="Output filename")
470
):
471
"""Safely write content to file."""
472
try:
473
with typer.open_file(filename, "w", atomic=True) as f:
474
f.write(content)
475
476
formatted_name = typer.format_filename(filename)
477
typer.secho(f"✓ Wrote to {formatted_name}", fg="green")
478
479
except Exception as e:
480
typer.secho(f"✗ Error writing file: {e}", fg="red", err=True)
481
raise typer.Exit(1)
482
483
if __name__ == "__main__":
484
typer.run(safe_file_write)
485
```
486
487
### Terminal Control
488
489
```python
490
import typer
491
import time
492
493
def terminal_demo():
494
"""Demonstrate terminal control functions."""
495
typer.echo("Terminal Demo Starting...")
496
time.sleep(2)
497
498
typer.clear()
499
typer.echo("Screen cleared!")
500
501
typer.echo("\\nPress any key to continue...")
502
char = typer.getchar()
503
typer.echo(f"You pressed: {char}")
504
505
if typer.confirm("Show large text via pager?"):
506
large_text = "\\n".join(f"Line {i}: Some content here" for i in range(100))
507
typer.echo_via_pager(large_text)
508
509
typer.pause("Press any key to exit...")
510
511
if __name__ == "__main__":
512
typer.run(terminal_demo)
513
```
514
515
### Text Editor Integration
516
517
```python
518
import typer
519
520
def edit_config():
521
"""Edit configuration using external editor."""
522
initial_config = """# Application Configuration
523
debug = false
524
host = localhost
525
port = 8000
526
"""
527
528
typer.echo("Opening editor for configuration...")
529
edited_config = typer.edit(initial_config, extension=".conf")
530
531
if edited_config:
532
typer.echo("Configuration updated:")
533
typer.echo(edited_config)
534
535
if typer.confirm("Save changes?"):
536
with open("config.conf", "w") as f:
537
f.write(edited_config)
538
typer.secho("Configuration saved!", fg="green")
539
else:
540
typer.secho("No changes made.", fg="yellow")
541
542
if __name__ == "__main__":
543
typer.run(edit_config)
544
```