0
# Termcolor
1
2
ANSI color formatting for output in terminal. Termcolor provides simple functions like `colored()` and `cprint()` to add colors, background colors, and text attributes (bold, underline, blink, etc.) to console text.
3
4
## Package Information
5
6
- **Package Name**: termcolor
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install termcolor`
10
11
## Core Imports
12
13
```python
14
from termcolor import colored, cprint
15
```
16
17
Import constants and utilities:
18
19
```python
20
from termcolor import COLORS, HIGHLIGHTS, ATTRIBUTES, RESET
21
```
22
23
Full import:
24
25
```python
26
from termcolor import ATTRIBUTES, COLORS, HIGHLIGHTS, RESET, colored, cprint
27
```
28
29
## Basic Usage
30
31
```python
32
from termcolor import colored, cprint
33
34
# Using colored() to format text
35
text = colored("Hello, World!", "red", attrs=["reverse", "blink"])
36
print(text)
37
38
# Using cprint() to print directly
39
cprint("Hello, World!", "green", "on_red")
40
41
# Create reusable formatting functions
42
print_red_on_cyan = lambda x: cprint(x, "red", "on_cyan")
43
print_red_on_cyan("Hello, World!")
44
print_red_on_cyan("Hello, Universe!")
45
46
# Using RGB colors
47
cprint("Custom purple text", (255, 0, 255))
48
cprint("Light pink text", (255, 182, 193))
49
50
# Multiple attributes
51
cprint("Bold underline reverse cyan", "cyan", attrs=["bold", "underline", "reverse"])
52
```
53
54
## Capabilities
55
56
### Text Coloring
57
58
Apply colors to text using predefined color names or custom RGB values.
59
60
```python { .api }
61
def colored(
62
text: object,
63
color: str | tuple[int, int, int] | None = None,
64
on_color: str | tuple[int, int, int] | None = None,
65
attrs: Iterable[str] | None = None,
66
*,
67
no_color: bool | None = None,
68
force_color: bool | None = None,
69
) -> str:
70
"""
71
Colorize text with ANSI color codes and return formatted string.
72
73
Available text colors:
74
black, red, green, yellow, blue, magenta, cyan, white,
75
light_grey, dark_grey, light_red, light_green, light_yellow, light_blue,
76
light_magenta, light_cyan.
77
78
Available text highlights:
79
on_black, on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white,
80
on_light_grey, on_dark_grey, on_light_red, on_light_green, on_light_yellow,
81
on_light_blue, on_light_magenta, on_light_cyan.
82
83
Available attributes:
84
bold, dark, underline, blink, reverse, concealed, strike.
85
86
Parameters:
87
- text: Text to colorize (converted to string)
88
- color: Text color (string from COLORS dict or RGB tuple with values 0-255)
89
- on_color: Background color (string from HIGHLIGHTS dict or RGB tuple with values 0-255)
90
- attrs: Text attributes (iterable of strings from ATTRIBUTES dict)
91
- no_color: Override to disable colors
92
- force_color: Override to enable colors
93
94
Returns:
95
Formatted string with ANSI codes
96
97
Example:
98
colored('Hello, World!', 'red', 'on_black', ['bold', 'blink'])
99
colored('Hello, World!', 'green')
100
colored('Hello, World!', (255, 0, 255)) # Purple
101
"""
102
```
103
104
### Direct Printing
105
106
Print colorized text directly to stdout.
107
108
```python { .api }
109
def cprint(
110
text: object,
111
color: str | tuple[int, int, int] | None = None,
112
on_color: str | tuple[int, int, int] | None = None,
113
attrs: Iterable[str] | None = None,
114
*,
115
no_color: bool | None = None,
116
force_color: bool | None = None,
117
**kwargs: Any,
118
) -> None:
119
"""
120
Print colorized text directly to stdout.
121
122
Parameters: Same as colored() plus any kwargs accepted by print()
123
124
Returns: None (prints to stdout)
125
"""
126
```
127
128
### Color Constants
129
130
Predefined dictionaries mapping color names to ANSI codes.
131
132
```python { .api }
133
COLORS: dict[str, int]
134
```
135
136
Available colors: `black`, `grey`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `light_grey`, `white`, `dark_grey`, `light_red`, `light_green`, `light_yellow`, `light_blue`, `light_magenta`, `light_cyan`.
137
138
Note: `grey` is an alias for `black`.
139
140
```python { .api }
141
HIGHLIGHTS: dict[str, int]
142
```
143
144
Available background colors: `on_black`, `on_grey`, `on_red`, `on_green`, `on_yellow`, `on_blue`, `on_magenta`, `on_cyan`, `on_light_grey`, `on_white`, `on_dark_grey`, `on_light_red`, `on_light_green`, `on_light_yellow`, `on_light_blue`, `on_light_magenta`, `on_light_cyan`.
145
146
Note: `on_grey` is an alias for `on_black`.
147
148
```python { .api }
149
ATTRIBUTES: dict[str, int]
150
```
151
152
Available text attributes: `bold`, `dark`, `underline`, `blink`, `reverse`, `concealed`, `strike`.
153
154
### Reset Sequence
155
156
ANSI reset sequence to clear text formatting.
157
158
```python { .api }
159
RESET: str
160
```
161
162
The ANSI reset sequence `"\033[0m"` used to reset text formatting.
163
164
## Types
165
166
```python { .api }
167
from collections.abc import Iterable
168
from typing import Any
169
```
170
171
## Color Control
172
173
Termcolor respects standard environment variables and provides override options:
174
175
- **Environment Variables**:
176
- `NO_COLOR`: Disables colors when set
177
- `ANSI_COLORS_DISABLED`: Disables colors when set
178
- `FORCE_COLOR`: Enables colors when set
179
- `TERM`: Disables colors when set to "dumb"
180
181
- **Override Parameters**:
182
- `no_color=True`: Disable colors for this call
183
- `force_color=True`: Enable colors for this call
184
185
## Command Line Usage
186
187
```bash
188
python -m termcolor
189
```
190
191
Displays a comprehensive demo showing all available colors, highlights, attributes, and RGB functionality.
192
193
## RGB Color Support
194
195
Both `color` and `on_color` parameters accept RGB tuples with values 0-255:
196
197
```python
198
from termcolor import cprint
199
200
# Custom colors using RGB tuples
201
cprint("Pure red text", (255, 0, 0))
202
cprint("Pure green text", (0, 255, 0))
203
cprint("Pure blue text", (0, 0, 255))
204
cprint("Light pink text", (255, 182, 193))
205
cprint("Custom purple text", (255, 0, 255))
206
207
# RGB background colors
208
cprint("Text on custom background", "white", (64, 128, 192))
209
```
210
211
## Error Handling
212
213
- **KeyError**: Raised when invalid color, highlight, or attribute names are used
214
- **TypeError**: Raised when invalid parameter types are passed
215
- **io.UnsupportedOperation**: Handled internally during terminal detection
216
217
## Platform Compatibility
218
219
- Cross-platform support (Windows, macOS, Linux)
220
- Automatic terminal capability detection
221
- Graceful fallback when colors are not supported
222
- Proper TTY detection and handling