or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

command-definition.mdcore-classes.mdexception-handling.mdindex.mdparameter-types.mdterminal-ui.mdutilities.md

terminal-ui.mddocs/

0

# Terminal UI and User Interaction

1

2

Interactive terminal functionality including prompts, confirmations, progress bars, styled output, and text editing capabilities. Click provides a comprehensive set of tools for creating engaging command-line user interfaces.

3

4

## Capabilities

5

6

### Output and Echo Functions

7

8

Basic output functions with enhanced features over standard print.

9

10

```python { .api }

11

def echo(message=None, file=None, nl=True, err=False, color=None):

12

"""

13

Print message with better support than print().

14

15

Parameters:

16

- message: Message to print (None prints empty line)

17

- file: File object to write to (defaults to stdout)

18

- nl: Whether to print trailing newline

19

- err: Write to stderr instead of stdout

20

- color: Force enable/disable color support

21

"""

22

23

def secho(message=None, file=None, nl=True, err=False, color=None, **styles):

24

"""

25

Styled echo that combines echo() and style().

26

27

Parameters:

28

- message: Message to print

29

- file: File object to write to

30

- nl: Whether to print trailing newline

31

- err: Write to stderr instead of stdout

32

- color: Force enable/disable color support

33

- **styles: Style arguments (fg, bg, bold, etc.)

34

"""

35

```

36

37

**Usage Examples:**

38

39

```python

40

@click.command()

41

def output_examples():

42

"""Demonstrate output functions."""

43

click.echo('Basic message')

44

click.echo('Error message', err=True)

45

click.echo('No newline', nl=False)

46

click.echo(' - continuation')

47

48

# Styled output

49

click.secho('Success!', fg='green', bold=True)

50

click.secho('Warning', fg='yellow')

51

click.secho('Error', fg='red', bold=True)

52

click.secho('Info', fg='blue', dim=True)

53

```

54

55

### Text Styling and Colors

56

57

Apply ANSI styling to terminal text with comprehensive color and formatting support.

58

59

```python { .api }

60

def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,

61

overline=None, italic=None, blink=None, reverse=None,

62

strikethrough=None, reset=True):

63

"""

64

Apply ANSI styles to text.

65

66

Parameters:

67

- text: Text to style

68

- fg: Foreground color (name, RGB tuple, or hex)

69

- bg: Background color (name, RGB tuple, or hex)

70

- bold: Bold text

71

- dim: Dim/faint text

72

- underline: Underlined text

73

- overline: Overlined text (limited support)

74

- italic: Italic text

75

- blink: Blinking text

76

- reverse: Reverse foreground/background

77

- strikethrough: Strikethrough text

78

- reset: Reset all styles at end

79

80

Returns:

81

Styled text string with ANSI codes

82

"""

83

84

def unstyle(text):

85

"""

86

Remove ANSI styling from text.

87

88

Parameters:

89

- text: Text with ANSI codes

90

91

Returns:

92

Plain text with ANSI codes removed

93

"""

94

```

95

96

**Available Colors:**

97

- Basic: black, red, green, yellow, blue, magenta, cyan, white

98

- Bright: bright_black, bright_red, bright_green, bright_yellow, bright_blue, bright_magenta, bright_cyan, bright_white

99

- RGB tuples: (255, 0, 0) for red

100

- Hex strings: '#ff0000' for red

101

102

**Usage Examples:**

103

104

```python

105

@click.command()

106

def styling_examples():

107

"""Demonstrate text styling."""

108

# Basic colors

109

click.echo(click.style('Red text', fg='red'))

110

click.echo(click.style('Green background', bg='green'))

111

112

# Text formatting

113

click.echo(click.style('Bold text', bold=True))

114

click.echo(click.style('Underlined text', underline=True))

115

click.echo(click.style('Italic text', italic=True))

116

click.echo(click.style('Dim text', dim=True))

117

118

# Combined styles

119

click.echo(click.style('Bold red on yellow', fg='red', bg='yellow', bold=True))

120

121

# RGB and hex colors

122

click.echo(click.style('RGB color', fg=(255, 165, 0))) # Orange

123

click.echo(click.style('Hex color', fg='#ff69b4')) # Hot pink

124

125

# Remove styling

126

styled_text = click.style('Styled text', fg='blue', bold=True)

127

plain_text = click.unstyle(styled_text)

128

click.echo(f'Original: {styled_text}')

129

click.echo(f'Unstyled: {plain_text}')

130

```

131

132

### Prompting and Input

133

134

Interactive input functions for gathering user data with validation and confirmation.

135

136

```python { .api }

137

def prompt(text, default=None, hide_input=False, confirmation_prompt=False,

138

type=None, value_proc=None, prompt_suffix=": ", show_default=True,

139

err=False, show_choices=True):

140

"""

141

Prompt user for input with validation.

142

143

Parameters:

144

- text: Prompt text to display

145

- default: Default value if user provides no input

146

- hide_input: Hide input (for passwords)

147

- confirmation_prompt: Prompt twice for confirmation

148

- type: ParamType for validation and conversion

149

- value_proc: Function to process the value

150

- prompt_suffix: Text to append to prompt

151

- show_default: Show default value in prompt

152

- err: Print prompt to stderr

153

- show_choices: Show choices for Choice types

154

155

Returns:

156

User input after validation and conversion

157

"""

158

159

def confirm(text, default=False, abort=False, prompt_suffix=": ",

160

show_default=True, err=False):

161

"""

162

Prompt for yes/no confirmation.

163

164

Parameters:

165

- text: Confirmation prompt text

166

- default: Default response (True/False)

167

- abort: Abort if user chooses no

168

- prompt_suffix: Text to append to prompt

169

- show_default: Show default in prompt

170

- err: Print prompt to stderr

171

172

Returns:

173

Boolean response

174

"""

175

```

176

177

**Usage Examples:**

178

179

```python

180

@click.command()

181

def prompt_examples():

182

"""Demonstrate prompting functions."""

183

# Basic prompts

184

name = click.prompt('Your name')

185

age = click.prompt('Your age', type=int)

186

187

# Default values

188

city = click.prompt('Your city', default='Unknown')

189

190

# Hidden input

191

password = click.prompt('Password', hide_input=True)

192

193

# Confirmation prompt

194

new_password = click.prompt('New password', hide_input=True,

195

confirmation_prompt=True)

196

197

# Type validation

198

email = click.prompt('Email', type=click.STRING)

199

port = click.prompt('Port', type=click.IntRange(1, 65535), default=8080)

200

201

# Choice prompts

202

level = click.prompt('Log level',

203

type=click.Choice(['DEBUG', 'INFO', 'WARNING', 'ERROR']))

204

205

# Confirmations

206

if click.confirm('Do you want to continue?'):

207

click.echo('Continuing...')

208

209

# Abort on no

210

click.confirm('Are you sure?', abort=True)

211

click.echo('User confirmed')

212

```

213

214

### Progress Indicators

215

216

Visual progress tracking for long-running operations.

217

218

```python { .api }

219

def progressbar(iterable=None, length=None, label=None, hidden=False,

220

show_eta=True, show_percent=None, show_pos=False,

221

item_show_func=None, fill_char="#", empty_char="-",

222

bar_template="%(label)s [%(bar)s] %(info)s",

223

info_sep=" ", width=36, file=None, color=None,

224

update_min_steps=1):

225

"""

226

Create a progress bar context manager.

227

228

Parameters:

229

- iterable: Iterable to track progress for

230

- length: Length of operation (if iterable not provided)

231

- label: Label to show before progress bar

232

- hidden: Hide progress bar completely

233

- show_eta: Show estimated time remaining

234

- show_percent: Show percentage complete

235

- show_pos: Show current position

236

- item_show_func: Function to display current item

237

- fill_char: Character for filled portion

238

- empty_char: Character for empty portion

239

- bar_template: Template string for bar format

240

- info_sep: Separator for info sections

241

- width: Width of progress bar

242

- file: File to write progress to

243

- color: Force enable/disable color

244

- update_min_steps: Minimum steps between updates

245

246

Returns:

247

ProgressBar context manager

248

"""

249

```

250

251

**Usage Examples:**

252

253

```python

254

import time

255

256

@click.command()

257

def progress_examples():

258

"""Demonstrate progress bars."""

259

# Basic progress with iterable

260

items = range(100)

261

with click.progressbar(items, label='Processing items') as bar:

262

for item in bar:

263

time.sleep(0.01) # Simulate work

264

265

# Manual progress updates

266

with click.progressbar(length=50, label='Manual progress') as bar:

267

for i in range(50):

268

# Do work

269

time.sleep(0.02)

270

bar.update(1)

271

272

# Custom styling

273

with click.progressbar(range(30),

274

label='Custom bar',

275

fill_char='█',

276

empty_char='░',

277

show_percent=True,

278

show_pos=True) as bar:

279

for item in bar:

280

time.sleep(0.05)

281

282

# With item display

283

def show_item(item):

284

return f'Item {item}'

285

286

with click.progressbar(range(20),

287

label='Items',

288

item_show_func=show_item) as bar:

289

for item in bar:

290

time.sleep(0.1)

291

```

292

293

### Interactive Features

294

295

Advanced interactive terminal features for enhanced user experience.

296

297

```python { .api }

298

def getchar(echo=False):

299

"""

300

Get a single character from terminal.

301

302

Parameters:

303

- echo: Whether to echo the character

304

305

Returns:

306

Single character string

307

"""

308

309

def pause(info=None, err=False):

310

"""

311

Pause execution until user presses a key.

312

313

Parameters:

314

- info: Custom message to display (default: "Press any key to continue...")

315

- err: Print message to stderr

316

"""

317

318

def edit(text=None, editor=None, env=None, require_save=True,

319

extension=".txt", filename=None):

320

"""

321

Open text in external editor.

322

323

Parameters:

324

- text: Initial text content

325

- editor: Editor command (defaults to $EDITOR environment variable)

326

- env: Environment variables for editor

327

- require_save: Require file to be saved

328

- extension: File extension for temporary file

329

- filename: Specific filename to use

330

331

Returns:

332

Edited text content

333

"""

334

335

def launch(url, wait=False, locate=False):

336

"""

337

Launch URL or file in default application.

338

339

Parameters:

340

- url: URL or file path to launch

341

- wait: Wait for application to close

342

- locate: Show file in file manager instead of opening

343

344

Returns:

345

Exit code of launched application

346

"""

347

```

348

349

**Usage Examples:**

350

351

```python

352

@click.command()

353

def interactive_examples():

354

"""Demonstrate interactive features."""

355

# Single character input

356

click.echo('Press any key...')

357

char = click.getchar()

358

click.echo(f'You pressed: {char}')

359

360

# Pause execution

361

click.pause('Press any key to continue with the demo...')

362

363

# Text editing

364

initial_text = "# Configuration\n\nEdit this text:\n"

365

edited_text = click.edit(initial_text, extension='.md')

366

if edited_text:

367

click.echo('You entered:')

368

click.echo(edited_text)

369

370

# Launch applications

371

if click.confirm('Open documentation in browser?'):

372

click.launch('https://click.palletsprojects.com/')

373

374

# Show file in file manager

375

if click.confirm('Show current directory?'):

376

click.launch('.', locate=True)

377

378

@click.command()

379

def editor_config():

380

"""Edit configuration file."""

381

config_text = """

382

# Application Configuration

383

debug = false

384

port = 8080

385

host = localhost

386

"""

387

388

click.echo('Opening configuration editor...')

389

result = click.edit(config_text, extension='.conf')

390

391

if result:

392

click.echo('Configuration updated:')

393

click.echo(result)

394

else:

395

click.echo('Configuration unchanged')

396

```

397

398

### Display and Paging

399

400

Functions for displaying large amounts of text with user-friendly paging.

401

402

```python { .api }

403

def echo_via_pager(text_or_generator, color=None):

404

"""

405

Display text through a pager (like 'less').

406

407

Parameters:

408

- text_or_generator: Text string or generator yielding lines

409

- color: Force enable/disable color in pager

410

"""

411

412

def clear():

413

"""Clear the terminal screen."""

414

```

415

416

**Usage Examples:**

417

418

```python

419

@click.command()

420

def display_examples():

421

"""Demonstrate display functions."""

422

# Clear screen

423

click.clear()

424

425

# Generate long text

426

long_text = '\n'.join([f'Line {i}: This is a long document with many lines.'

427

for i in range(100)])

428

429

# Display via pager

430

click.echo('Displaying long text via pager...')

431

click.echo_via_pager(long_text)

432

433

# Generator example

434

def generate_lines():

435

for i in range(50):

436

yield f'Generated line {i}: Some content here'

437

if i % 10 == 0:

438

yield click.style(f'--- Section {i//10} ---', bold=True)

439

440

click.echo('Displaying generated content...')

441

click.echo_via_pager(generate_lines())

442

```