Simple and elegant wrapper for colorama providing terminal text coloring functionality
npx @tessl/cli install tessl/pypi-crayons@0.4.00
# Crayons
1
2
Simple and elegant wrapper for colorama providing terminal text coloring functionality. Crayons automatically handles foreground color application and state restoration, eliminating manual color management typically required with terminal color libraries.
3
4
## Package Information
5
6
- **Package Name**: crayons
7
- **Language**: Python
8
- **Installation**: `pip install crayons`
9
- **Dependencies**: colorama
10
11
## Core Imports
12
13
```python
14
import crayons
15
```
16
17
Individual color functions and utilities:
18
19
```python
20
from crayons import red, green, blue, yellow, magenta, cyan, white, black, normal
21
from crayons import clean, disable, enable, random, replace_colors, reset_replace_colors
22
from crayons import ColoredString
23
```
24
25
Or import all:
26
27
```python
28
from crayons import *
29
```
30
31
## Basic Usage
32
33
```python
34
import crayons
35
36
# Basic colored text
37
print(crayons.red('This text is red'))
38
print(crayons.green('This text is green'))
39
print(crayons.blue('This text is blue'))
40
41
# Bold text
42
print(crayons.yellow('Bold yellow text', bold=True))
43
44
# Force color output even when piped
45
print(crayons.magenta('Always colored', always=True))
46
47
# Mix colors in output
48
print('{} and {} text'.format(crayons.red('red'), crayons.blue('blue')))
49
50
# Random colors
51
print(crayons.random('This text has a random color'))
52
53
# Global control
54
crayons.disable() # Turn off all colors
55
print(crayons.red('This will not be colored'))
56
crayons.enable() # Turn colors back on
57
58
# Clean ANSI codes from strings
59
colored_text = crayons.red('colored')
60
clean_text = crayons.clean(str(colored_text))
61
print(clean_text) # Prints without color codes
62
```
63
64
## Capabilities
65
66
### Color Functions
67
68
Eight standard color functions that create colored text strings. Each function accepts text and optional formatting parameters.
69
70
```python { .api }
71
def red(s, always=False, bold=False):
72
"""
73
Create red colored text.
74
75
Parameters:
76
- s: str or any object convertible to string, text to color
77
- always: bool, force color output even when not in TTY (default: False)
78
- bold: bool, make text bold (default: False)
79
80
Returns:
81
ColoredString object with red foreground color
82
"""
83
84
def green(s, always=False, bold=False):
85
"""
86
Create green colored text.
87
88
Parameters:
89
- s: str or any object convertible to string, text to color
90
- always: bool, force color output even when not in TTY (default: False)
91
- bold: bool, make text bold (default: False)
92
93
Returns:
94
ColoredString object with green foreground color
95
"""
96
97
def yellow(s, always=False, bold=False):
98
"""
99
Create yellow colored text.
100
101
Parameters:
102
- s: str or any object convertible to string, text to color
103
- always: bool, force color output even when not in TTY (default: False)
104
- bold: bool, make text bold (default: False)
105
106
Returns:
107
ColoredString object with yellow foreground color
108
"""
109
110
def blue(s, always=False, bold=False):
111
"""
112
Create blue colored text.
113
114
Parameters:
115
- s: str or any object convertible to string, text to color
116
- always: bool, force color output even when not in TTY (default: False)
117
- bold: bool, make text bold (default: False)
118
119
Returns:
120
ColoredString object with blue foreground color
121
"""
122
123
def black(s, always=False, bold=False):
124
"""
125
Create black colored text.
126
127
Parameters:
128
- s: str or any object convertible to string, text to color
129
- always: bool, force color output even when not in TTY (default: False)
130
- bold: bool, make text bold (default: False)
131
132
Returns:
133
ColoredString object with black foreground color
134
"""
135
136
def magenta(s, always=False, bold=False):
137
"""
138
Create magenta colored text.
139
140
Parameters:
141
- s: str or any object convertible to string, text to color
142
- always: bool, force color output even when not in TTY (default: False)
143
- bold: bool, make text bold (default: False)
144
145
Returns:
146
ColoredString object with magenta foreground color
147
"""
148
149
def cyan(s, always=False, bold=False):
150
"""
151
Create cyan colored text.
152
153
Parameters:
154
- s: str or any object convertible to string, text to color
155
- always: bool, force color output even when not in TTY (default: False)
156
- bold: bool, make text bold (default: False)
157
158
Returns:
159
ColoredString object with cyan foreground color
160
"""
161
162
def white(s, always=False, bold=False):
163
"""
164
Create white colored text.
165
166
Parameters:
167
- s: str or any object convertible to string, text to color
168
- always: bool, force color output even when not in TTY (default: False)
169
- bold: bool, make text bold (default: False)
170
171
Returns:
172
ColoredString object with white foreground color
173
"""
174
175
def normal(s, always=False, bold=False):
176
"""
177
Create text with normal/reset color (default terminal foreground color).
178
179
Parameters:
180
- s: str or any object convertible to string, text to color
181
- always: bool, force color output even when not in TTY (default: False)
182
- bold: bool, make text bold (default: False)
183
184
Returns:
185
ColoredString object with reset/normal foreground color
186
"""
187
```
188
189
### Utility Functions
190
191
Functions for controlling color behavior, cleaning ANSI codes, and selecting random colors.
192
193
```python { .api }
194
def clean(s):
195
"""
196
Remove ANSI color codes from a string.
197
198
Parameters:
199
- s: str, string potentially containing ANSI color codes
200
201
Returns:
202
str with all ANSI escape sequences removed
203
"""
204
205
def random(string, always=False, bold=False, colors=COLORS):
206
"""
207
Select a color at random from available colors.
208
209
Parameters:
210
- string: str or any object convertible to string, text to color
211
- always: bool, force color output even when not in TTY (default: False)
212
- bold: bool, make text bold (default: False)
213
- colors: list of str, color names to choose from (default: all standard colors)
214
215
Returns:
216
ColoredString object with randomly selected color
217
"""
218
219
def disable():
220
"""
221
Globally disable all color output. All color functions will return plain text.
222
223
Returns:
224
None
225
"""
226
227
def enable():
228
"""
229
Globally enable color output (default state).
230
231
Returns:
232
None
233
"""
234
235
def replace_colors(replace_dict):
236
"""
237
Replace color mappings with custom colors for background customization.
238
239
Parameters:
240
- replace_dict: dict, mapping of original color names to replacement color names
241
(e.g., {'magenta': 'blue', 'red': 'green'})
242
243
Returns:
244
None
245
246
Raises:
247
AssertionError: if replace_dict is not a dictionary
248
"""
249
250
def reset_replace_colors():
251
"""
252
Reset any custom color mappings back to defaults.
253
254
Returns:
255
None
256
"""
257
```
258
259
### ColoredString Class
260
261
Enhanced string class that handles colored text output with proper length calculations and string operations.
262
263
```python { .api }
264
class ColoredString:
265
"""
266
Enhanced string for colored output with proper __len__ operations.
267
268
Supports all standard string methods while preserving color information.
269
Automatically handles TTY detection and color output control.
270
"""
271
272
def __init__(self, color, s, always_color=False, bold=False):
273
"""
274
Initialize a colored string.
275
276
Parameters:
277
- color: str, color name (e.g., 'RED', 'GREEN', 'BLUE')
278
- s: str or any object convertible to string, text content
279
- always_color: bool, force color output even when not in TTY (default: False)
280
- bold: bool, make text bold (default: False)
281
"""
282
283
@property
284
def color_str(self):
285
"""
286
Get the colored string with ANSI codes or plain text based on TTY detection.
287
288
Returns:
289
str with ANSI color codes if in TTY and colors enabled, otherwise plain text
290
"""
291
292
def __len__(self):
293
"""
294
Return length of plain text content without ANSI codes.
295
296
Returns:
297
int, length of the underlying text string
298
"""
299
300
def __unicode__(self):
301
"""
302
Unicode string representation with color codes if appropriate.
303
304
Returns:
305
unicode string (Python 2) or str (Python 3) with color codes or plain text
306
"""
307
308
def __str__(self):
309
"""
310
String representation with color codes if appropriate.
311
312
Returns:
313
str, colored string or plain text based on output context
314
"""
315
316
def __repr__(self):
317
"""
318
Debug representation showing color and content.
319
320
Returns:
321
str in format "<COLOR-string: 'content'>"
322
"""
323
324
def __add__(self, other):
325
"""
326
Concatenate colored string with another string.
327
328
Parameters:
329
- other: str or any string-like object
330
331
Returns:
332
str, concatenated result
333
"""
334
335
def __radd__(self, other):
336
"""
337
Reverse concatenation (other + self).
338
339
Parameters:
340
- other: str or any string-like object
341
342
Returns:
343
str, concatenated result
344
"""
345
346
def __mul__(self, other):
347
"""
348
Repeat colored string multiple times.
349
350
Parameters:
351
- other: int, number of repetitions
352
353
Returns:
354
str, repeated colored string
355
"""
356
357
def __iter__(self):
358
"""
359
Iterate over characters in the colored string.
360
361
Returns:
362
iterator over characters in color_str
363
"""
364
365
def __getattr__(self, name):
366
"""
367
Delegate string methods to underlying string while preserving color.
368
369
All standard string methods (split, replace, upper, lower, etc.) are available
370
and return new ColoredString objects when the result is a string.
371
372
Parameters:
373
- name: str, name of the string method to call
374
375
Returns:
376
ColoredString for string results, original return type for non-string results
377
"""
378
```
379
380
## Constants
381
382
```python { .api }
383
COLORS = ('red', 'green', 'yellow', 'blue', 'black', 'magenta', 'cyan', 'white')
384
"""Tuple of available color names for use with random() function and color replacement."""
385
```
386
387
## Environment Variables
388
389
- **CLINT_FORCE_COLOR**: Forces color output even when not in TTY
390
- **TERM**: Colors are disabled when set to "dumb"
391
392
## Key Features
393
394
- **Automatic TTY Detection**: Colors automatically disabled when output is piped or redirected
395
- **iPython Compatibility**: Colors automatically disabled in iPython environments
396
- **Cross-platform Support**: Built on colorama for Windows, macOS, and Linux compatibility
397
- **Length Calculation**: ColoredString objects return correct length without ANSI codes
398
- **String Operations**: ColoredString supports concatenation, multiplication, and iteration
399
- **Global Control**: Enable/disable all colors globally with simple function calls
400
- **Color Customization**: Replace default colors with custom mappings for different backgrounds
401
- **Bold Text Support**: All color functions support bold text styling
402
- **Random Colors**: Built-in random color selection for dynamic applications
403
- **Python Compatibility**: Supports Python 2.7+ and 3.x
404
405
## Error Handling
406
407
The library is designed to be fault-tolerant:
408
409
- Non-string inputs are automatically converted to strings
410
- Invalid color names in replacement dictionaries are handled gracefully
411
- TTY detection failures fall back to no-color output
412
- Unicode handling works across Python 2 and 3