or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Colorama

1

2

A Python library that enables cross-platform colored terminal text output by making ANSI escape character sequences work on MS Windows. On Unix and Mac platforms, colorama does nothing and allows native ANSI support to work unchanged, providing a simple cross-platform API for printing colored terminal text.

3

4

## Package Information

5

6

- **Package Name**: colorama

7

- **Language**: Python

8

- **Installation**: `pip install colorama`

9

- **Python Support**: 2.7, 3.7+

10

- **Platform Support**: Windows, Unix, Mac (cross-platform)

11

12

## Core Imports

13

14

```python

15

import colorama

16

from colorama import init, just_fix_windows_console, deinit, reinit, colorama_text

17

from colorama import Fore, Back, Style, Cursor, AnsiToWin32

18

from colorama import code_to_chars, set_title, clear_screen, clear_line

19

```

20

21

Alternative for Windows-only fix:

22

23

```python

24

from colorama import just_fix_windows_console

25

just_fix_windows_console()

26

```

27

28

## Basic Usage

29

30

```python

31

from colorama import init, Fore, Back, Style

32

33

# Initialize colorama

34

init()

35

36

# Simple colored text

37

print(Fore.RED + 'Hello World!' + Style.RESET_ALL)

38

print(Back.GREEN + 'Green background' + Style.RESET_ALL)

39

print(Style.BRIGHT + 'Bright text' + Style.RESET_ALL)

40

41

# Combining colors and styles

42

print(Fore.YELLOW + Back.BLUE + Style.BRIGHT + 'Yellow on blue, bright' + Style.RESET_ALL)

43

44

# Context manager usage

45

from colorama import colorama_text

46

with colorama_text():

47

print(Fore.CYAN + 'This will be cyan')

48

# Automatically deinitialized

49

```

50

51

## Capabilities

52

53

### Initialization and Configuration

54

55

Configure colorama behavior and enable cross-platform ANSI support.

56

57

```python { .api }

58

def init(autoreset=False, convert=None, strip=None, wrap=True):

59

"""

60

Initialize colorama.

61

62

Args:

63

autoreset (bool): Auto-reset colors after each print. Default: False

64

convert (bool|None): Convert ANSI sequences to Win32 calls. Default: None (auto-detect)

65

strip (bool|None): Strip ANSI sequences from output. Default: None (auto-detect)

66

wrap (bool): Wrap stdout/stderr streams. Default: True

67

68

Returns:

69

None

70

71

Raises:

72

ValueError: If wrap=False conflicts with any other arg=True

73

"""

74

75

def deinit():

76

"""

77

De-initialize colorama, restore original stdout/stderr streams.

78

79

Returns:

80

None

81

"""

82

83

def reinit():

84

"""

85

Re-initialize colorama with previous settings.

86

87

Returns:

88

None

89

"""

90

91

def just_fix_windows_console():

92

"""

93

Minimal fix for Windows console ANSI support.

94

95

On newer Windows versions, enables native ANSI support.

96

On older versions, wraps streams only if needed.

97

Does nothing on non-Windows platforms.

98

99

Returns:

100

None

101

"""

102

103

def colorama_text(*args, **kwargs):

104

"""

105

Context manager for temporary colorama usage.

106

107

Args:

108

*args, **kwargs: Same arguments as init()

109

110

Returns:

111

Context manager that calls init() on enter and deinit() on exit

112

"""

113

```

114

115

### Foreground Colors

116

117

Set text foreground colors using ANSI escape sequences.

118

119

```python { .api }

120

class Fore:

121

"""Foreground color constants."""

122

BLACK: str # Black text

123

RED: str # Red text

124

GREEN: str # Green text

125

YELLOW: str # Yellow text

126

BLUE: str # Blue text

127

MAGENTA: str # Magenta text

128

CYAN: str # Cyan text

129

WHITE: str # White text

130

RESET: str # Reset to default foreground color

131

132

# Extended colors (may not be supported on all terminals)

133

LIGHTBLACK_EX: str # Light black text

134

LIGHTRED_EX: str # Light red text

135

LIGHTGREEN_EX: str # Light green text

136

LIGHTYELLOW_EX: str # Light yellow text

137

LIGHTBLUE_EX: str # Light blue text

138

LIGHTMAGENTA_EX: str # Light magenta text

139

LIGHTCYAN_EX: str # Light cyan text

140

LIGHTWHITE_EX: str # Light white text

141

```

142

143

### Background Colors

144

145

Set text background colors using ANSI escape sequences.

146

147

```python { .api }

148

class Back:

149

"""Background color constants."""

150

BLACK: str # Black background

151

RED: str # Red background

152

GREEN: str # Green background

153

YELLOW: str # Yellow background

154

BLUE: str # Blue background

155

MAGENTA: str # Magenta background

156

CYAN: str # Cyan background

157

WHITE: str # White background

158

RESET: str # Reset to default background color

159

160

# Extended colors (may not be supported on all terminals)

161

LIGHTBLACK_EX: str # Light black background

162

LIGHTRED_EX: str # Light red background

163

LIGHTGREEN_EX: str # Light green background

164

LIGHTYELLOW_EX: str # Light yellow background

165

LIGHTBLUE_EX: str # Light blue background

166

LIGHTMAGENTA_EX: str # Light magenta background

167

LIGHTCYAN_EX: str # Light cyan background

168

LIGHTWHITE_EX: str # Light white background

169

```

170

171

### Text Styling

172

173

Control text brightness and styling with ANSI escape sequences.

174

175

```python { .api }

176

class Style:

177

"""Text style constants."""

178

BRIGHT: str # Bright/bold text

179

DIM: str # Dim text (may appear same as normal on Windows)

180

NORMAL: str # Normal brightness text

181

RESET_ALL: str # Reset all formatting (colors and styles)

182

```

183

184

### Cursor Positioning

185

186

Control cursor movement and positioning in the terminal.

187

188

```python { .api }

189

class Cursor:

190

"""Cursor positioning methods."""

191

192

def UP(n=1):

193

"""

194

Move cursor up n lines.

195

196

Args:

197

n (int): Number of lines to move up. Default: 1

198

199

Returns:

200

str: ANSI escape sequence for cursor movement

201

"""

202

203

def DOWN(n=1):

204

"""

205

Move cursor down n lines.

206

207

Args:

208

n (int): Number of lines to move down. Default: 1

209

210

Returns:

211

str: ANSI escape sequence for cursor movement

212

"""

213

214

def FORWARD(n=1):

215

"""

216

Move cursor forward n columns.

217

218

Args:

219

n (int): Number of columns to move forward. Default: 1

220

221

Returns:

222

str: ANSI escape sequence for cursor movement

223

"""

224

225

def BACK(n=1):

226

"""

227

Move cursor back n columns.

228

229

Args:

230

n (int): Number of columns to move back. Default: 1

231

232

Returns:

233

str: ANSI escape sequence for cursor movement

234

"""

235

236

def POS(x=1, y=1):

237

"""

238

Set cursor position to specific coordinates.

239

240

Args:

241

x (int): Column position (1-based). Default: 1

242

y (int): Row position (1-based). Default: 1

243

244

Returns:

245

str: ANSI escape sequence for cursor positioning

246

"""

247

```

248

249

### ANSI Utility Functions

250

251

Low-level functions for generating ANSI escape sequences and terminal control.

252

253

```python { .api }

254

def code_to_chars(code):

255

"""

256

Convert an ANSI code number to ANSI escape sequence string.

257

258

Args:

259

code (int): ANSI code number

260

261

Returns:

262

str: ANSI escape sequence (e.g., '\033[31m' for red foreground)

263

"""

264

265

def set_title(title):

266

"""

267

Generate ANSI sequence to set terminal window title.

268

269

Args:

270

title (str): Terminal title to set

271

272

Returns:

273

str: ANSI escape sequence for setting title

274

"""

275

276

def clear_screen(mode=2):

277

"""

278

Generate ANSI sequence to clear terminal screen.

279

280

Args:

281

mode (int): Clear mode - 0: cursor to end, 1: start to cursor, 2: entire screen. Default: 2

282

283

Returns:

284

str: ANSI escape sequence for screen clearing

285

"""

286

287

def clear_line(mode=2):

288

"""

289

Generate ANSI sequence to clear terminal line.

290

291

Args:

292

mode (int): Clear mode - 0: cursor to end, 1: start to cursor, 2: entire line. Default: 2

293

294

Returns:

295

str: ANSI escape sequence for line clearing

296

"""

297

```

298

299

### Advanced Windows Integration

300

301

For advanced use cases requiring direct access to Windows conversion functionality.

302

303

```python { .api }

304

class AnsiToWin32:

305

"""

306

ANSI to Win32 conversion wrapper for Windows terminals.

307

308

Wraps a stream (typically stdout/stderr) and converts ANSI escape

309

sequences to appropriate Win32 console API calls on Windows.

310

"""

311

312

def __init__(wrapped, convert=None, strip=None, autoreset=False):

313

"""

314

Initialize ANSI to Win32 converter.

315

316

Args:

317

wrapped: The stream to wrap (e.g., sys.stdout)

318

convert (bool|None): Convert ANSI to Win32 calls. Default: None (auto-detect)

319

strip (bool|None): Strip ANSI sequences. Default: None (auto-detect)

320

autoreset (bool): Auto-reset after each write. Default: False

321

"""

322

323

# Properties

324

stream: object # The wrapped stream proxy

325

wrapped: object # The original stream

326

convert: bool # Whether to convert ANSI sequences to Win32 calls

327

strip: bool # Whether to strip ANSI sequences from output

328

autoreset: bool # Whether to auto-reset colors after each write

329

on_stderr: bool # Whether this wraps stderr (vs stdout)

330

331

def write(text):

332

"""

333

Write text to wrapped stream with ANSI conversion.

334

335

Args:

336

text (str): Text to write

337

338

Returns:

339

None

340

"""

341

342

def flush():

343

"""

344

Flush the wrapped stream.

345

346

Returns:

347

None

348

"""

349

350

def reset_all():

351

"""

352

Reset all terminal formatting.

353

354

Returns:

355

None

356

"""

357

358

def should_wrap():

359

"""

360

Check if stream wrapping is actually needed.

361

362

Returns:

363

bool: True if wrapping provides functionality, False otherwise

364

"""

365

```

366

367

## Usage Examples

368

369

### Simple Color Output

370

371

```python

372

from colorama import init, Fore, Back, Style

373

374

init()

375

376

# Basic colors

377

print(Fore.RED + "Error: Something went wrong" + Style.RESET_ALL)

378

print(Fore.GREEN + "Success: Operation completed" + Style.RESET_ALL)

379

print(Fore.YELLOW + "Warning: Please check this" + Style.RESET_ALL)

380

381

# Background colors

382

print(Back.BLUE + Fore.WHITE + "White text on blue background" + Style.RESET_ALL)

383

384

# Bright/dim styles

385

print(Style.BRIGHT + Fore.RED + "Bright red text" + Style.RESET_ALL)

386

print(Style.DIM + "Dim text" + Style.RESET_ALL)

387

```

388

389

### Auto-reset Mode

390

391

```python

392

from colorama import init, Fore, Back, Style

393

394

# Enable auto-reset - colors reset after each print

395

init(autoreset=True)

396

397

print(Fore.RED + "This will be red")

398

print("This will be normal color") # No need for Style.RESET_ALL

399

print(Back.GREEN + "Green background")

400

print("Normal background again")

401

```

402

403

### Context Manager Usage

404

405

```python

406

from colorama import colorama_text, Fore, Style

407

408

# Temporary colorama initialization

409

with colorama_text(autoreset=True):

410

print(Fore.CYAN + "Cyan text")

411

print(Style.BRIGHT + "Bright text")

412

# Colorama automatically deinitialized here

413

414

print("Normal text - colorama not active")

415

```

416

417

### Cursor Movement

418

419

```python

420

from colorama import init, Cursor, Fore

421

422

init()

423

424

print("Line 1")

425

print("Line 2")

426

print("Line 3")

427

428

# Move cursor up and overwrite

429

print(Cursor.UP(2) + Cursor.FORWARD(5) + Fore.RED + "CHANGED" + Fore.RESET)

430

431

# Set specific position

432

print(Cursor.POS(10, 1) + "At column 10, row 1")

433

```

434

435

### ANSI Utility Functions Usage

436

437

```python

438

from colorama import init, code_to_chars, set_title, clear_screen, clear_line, Fore

439

440

init()

441

442

# Manual ANSI code generation

443

red_code = code_to_chars(31) # '\033[31m'

444

print(red_code + "Manual red text" + code_to_chars(0)) # Reset with code 0

445

446

# Set terminal title

447

title_sequence = set_title("My Python Application")

448

print(title_sequence, end='') # Set title without newline

449

450

# Clear screen

451

print("Some text that will be cleared...")

452

print(clear_screen(), end='') # Clear entire screen

453

454

# Clear line

455

print("This line will be partially cleared", end='')

456

print(clear_line(0), end='') # Clear from cursor to end of line

457

print("New text on same line")

458

```

459

460

### Minimal Windows Fix

461

462

```python

463

from colorama import just_fix_windows_console

464

465

# Just enable Windows ANSI support without other colorama features

466

just_fix_windows_console()

467

468

# Now ANSI sequences work on Windows

469

print('\033[31mRed text\033[0m') # Raw ANSI sequences

470

print('\033[32mGreen text\033[0m')

471

```

472

473

## Types

474

475

```python { .api }

476

# All color and style constants are strings containing ANSI escape sequences

477

Fore.RED: str = '\033[31m'

478

Back.BLUE: str = '\033[44m'

479

Style.BRIGHT: str = '\033[1m'

480

Style.RESET_ALL: str = '\033[0m'

481

482

# Cursor methods return ANSI escape sequence strings

483

Cursor.UP(2): str = '\033[2A'

484

Cursor.POS(5, 3): str = '\033[3;5H'

485

486

# Utility functions return ANSI escape sequence strings

487

code_to_chars(31): str = '\033[31m'

488

set_title("Title"): str = '\033]2;Title\a'

489

clear_screen(): str = '\033[2J'

490

clear_line(): str = '\033[2K'

491

492

# Initialization functions return None

493

init(): None

494

deinit(): None

495

just_fix_windows_console(): None

496

```

497

498

## Constants

499

500

```python { .api }

501

# Access via colorama module import

502

import colorama

503

colorama.__version__: str = '0.4.6' # Package version

504

505

# Or access directly

506

from colorama import __version__

507

__version__: str = '0.4.6'

508

```

509

510

## Error Handling

511

512

The library handles errors gracefully:

513

514

- `init()` raises `ValueError` if `wrap=False` conflicts with other `True` arguments

515

- Windows-specific functionality gracefully degrades on non-Windows platforms

516

- Missing Windows APIs fall back to no-op behavior

517

- Stream wrapping is automatically detected based on terminal capabilities

518

519

## Platform Behavior

520

521

- **Windows**: Converts ANSI sequences to Win32 console API calls, or enables native ANSI support on newer versions

522

- **Unix/Mac**: Passes ANSI sequences through unchanged to leverage native terminal support

523

- **All platforms**: Provides consistent API regardless of underlying implementation