0
# Color and Terminal Support
1
2
ANSI color system with automatic terminal capability detection and pre-defined color schemes for different environments and preferences. Provides comprehensive color support across platforms including Windows, macOS, and Linux terminals.
3
4
## Capabilities
5
6
### Terminal Capability Detection
7
8
Automatically detect if a terminal or file supports ANSI color codes across different platforms.
9
10
```python { .api }
11
def supports_ansi(file_: TextIO) -> bool:
12
"""
13
Detect if a file or terminal supports ANSI color codes.
14
15
Checks multiple conditions across platforms:
16
- Terminal TTY capability
17
- Windows Terminal support (VirtualTerminalLevel, Windows Terminal, VS Code, ANSICON)
18
- Platform-specific color support detection
19
20
Parameters:
21
- file_: File-like object to test (typically sys.stdout or sys.stderr)
22
23
Returns:
24
True if ANSI colors are supported, False otherwise
25
"""
26
```
27
28
### Color Scheme Configuration
29
30
Define and configure ANSI color schemes for different traceback elements.
31
32
```python { .api }
33
class ColorScheme:
34
def __init__(
35
self,
36
common: str, # General text color
37
file_: str, # File path color
38
line_num: str, # Line number color
39
func_name: str, # Function name color
40
func_snippet: str, # Source code color
41
name: str, # Variable name color
42
value: str, # Variable value color
43
exc_class: str, # Exception class color
44
exc_text: str, # Exception message color
45
end: str, # Reset/end color
46
):
47
"""
48
Create a color scheme with ANSI color codes for traceback elements.
49
50
Each parameter accepts ANSI color code strings (e.g., '31' for red,
51
'32;1' for bright green). Empty strings disable coloring for that element.
52
53
The class automatically creates convenient attributes:
54
- c, f, ln, fn, fs, n, v, ec, et, e: Direct color codes
55
- c_, f_, ln_, fn_, fs_, n_, v_, ec_, et_: Color codes with reset prefixes
56
"""
57
```
58
59
### Pre-defined Color Schemes
60
61
Collection of ready-to-use color schemes for different environments and preferences.
62
63
```python { .api }
64
class ColorSchemes:
65
auto: None
66
"""Auto-detect appropriate color scheme based on terminal capabilities."""
67
68
none: ColorScheme
69
"""No colors - plain text output suitable for files and non-color terminals."""
70
71
common: ColorScheme
72
"""Standard color scheme with good compatibility across terminals."""
73
74
synthwave: ColorScheme
75
"""Retro synthwave color scheme with bright neon colors."""
76
77
nice: ColorScheme
78
"""Subtle, pleasant color scheme with muted tones."""
79
```
80
81
## Usage Examples
82
83
### Automatic Color Detection
84
85
```python
86
from traceback_with_variables import Format, ColorSchemes, print_exc
87
import sys
88
89
# Auto-detect color support
90
if supports_ansi(sys.stderr):
91
fmt = Format(color_scheme=ColorSchemes.common)
92
print("Colors enabled!")
93
else:
94
fmt = Format(color_scheme=ColorSchemes.none)
95
print("No color support detected")
96
97
try:
98
data = {"numbers": [1, 2, 3]}
99
result = data["missing"]
100
except Exception as e:
101
print_exc(e, fmt=fmt)
102
```
103
104
### Color Scheme Comparison
105
106
```python
107
from traceback_with_variables import Format, ColorSchemes, print_exc
108
109
# Test different color schemes
110
schemes = {
111
"No Colors": ColorSchemes.none,
112
"Common": ColorSchemes.common,
113
"Synthwave": ColorSchemes.synthwave,
114
"Nice": ColorSchemes.nice
115
}
116
117
def test_exception():
118
user_data = {"id": 123, "name": "Alice", "preferences": {"theme": "dark"}}
119
missing_value = user_data["settings"]["notification"]
120
121
for scheme_name, scheme in schemes.items():
122
print(f"\n=== {scheme_name} Color Scheme ===")
123
fmt = Format(color_scheme=scheme)
124
125
try:
126
test_exception()
127
except Exception as e:
128
print_exc(e, fmt=fmt)
129
```
130
131
### Custom Color Scheme Creation
132
133
```python
134
from traceback_with_variables import ColorScheme, Format, print_exc
135
136
# Create custom color scheme
137
custom_scheme = ColorScheme(
138
common='0', # Normal text
139
file_='94', # Bright blue for files
140
line_num='93', # Bright yellow for line numbers
141
func_name='95', # Bright magenta for functions
142
func_snippet='37', # White for source code
143
name='96', # Bright cyan for variable names
144
value='92', # Bright green for values
145
exc_class='91', # Bright red for exception class
146
exc_text='31', # Red for exception message
147
end='0' # Reset
148
)
149
150
# Use custom scheme
151
custom_fmt = Format(color_scheme=custom_scheme)
152
153
try:
154
config = {"database": {"host": "localhost", "port": 5432}}
155
connection_string = config["database"]["password"]
156
except Exception as e:
157
print_exc(e, fmt=custom_fmt)
158
```
159
160
### Environment-Specific Color Configuration
161
162
```python
163
from traceback_with_variables import Format, ColorSchemes, supports_ansi
164
import sys
165
import os
166
167
def get_appropriate_color_scheme():
168
"""Select color scheme based on environment."""
169
170
# Check if we're in a specific environment
171
if os.getenv('TERM_PROGRAM') == 'vscode':
172
return ColorSchemes.nice # VS Code integrated terminal
173
174
elif os.getenv('JUPYTER_SERVER_ROOT'):
175
return ColorSchemes.common # Jupyter environment
176
177
elif 'WT_SESSION' in os.environ:
178
return ColorSchemes.synthwave # Windows Terminal
179
180
elif supports_ansi(sys.stderr):
181
return ColorSchemes.common # Generic color terminal
182
183
else:
184
return ColorSchemes.none # No color support
185
186
# Apply environment-appropriate colors
187
env_fmt = Format(color_scheme=get_appropriate_color_scheme())
188
189
try:
190
project_config = {
191
"version": "1.0.0",
192
"dependencies": ["requests", "numpy"],
193
"dev_dependencies": ["pytest", "black"]
194
}
195
missing_config = project_config["build"]["target"]
196
except Exception as e:
197
print_exc(e, fmt=env_fmt)
198
```
199
200
### File vs Terminal Color Handling
201
202
```python
203
from traceback_with_variables import Format, ColorSchemes, supports_ansi, print_exc
204
import sys
205
206
def create_format_for_output(output_file):
207
"""Create appropriate format based on output destination."""
208
if supports_ansi(output_file):
209
return Format(color_scheme=ColorSchemes.common)
210
else:
211
return Format(color_scheme=ColorSchemes.none)
212
213
# Different outputs get appropriate formatting
214
try:
215
api_data = {"users": [{"id": 1, "name": "Alice"}], "total": 1}
216
user = api_data["users"][5] # Index error
217
218
except Exception as e:
219
# Terminal output with colors
220
terminal_fmt = create_format_for_output(sys.stderr)
221
print("=== Terminal Output (with colors if supported) ===")
222
print_exc(e, fmt=terminal_fmt)
223
224
# File output without colors
225
with open('/tmp/error.log', 'w') as log_file:
226
file_fmt = create_format_for_output(log_file)
227
print("\n=== File Output (no colors) ===")
228
print_exc(e, fmt=file_fmt, file_=log_file)
229
```
230
231
### Color Scheme Testing Utility
232
233
```python
234
from traceback_with_variables import ColorScheme, Format, print_exc
235
236
def test_color_scheme(scheme: ColorScheme, name: str):
237
"""Test a color scheme with sample traceback."""
238
print(f"\n{'='*50}")
239
print(f"Testing {name} Color Scheme")
240
print('='*50)
241
242
fmt = Format(color_scheme=scheme, before=1, after=1)
243
244
def sample_function():
245
sample_dict = {"key1": "value1", "key2": [1, 2, 3]}
246
sample_list = ["item1", "item2", "item3"]
247
sample_number = 42
248
sample_string = "Hello, World!"
249
250
# Trigger error to show all variables
251
return sample_dict["nonexistent_key"]
252
253
try:
254
sample_function()
255
except Exception as e:
256
print_exc(e, fmt=fmt)
257
258
# Test all built-in schemes
259
from traceback_with_variables import ColorSchemes
260
261
test_color_scheme(ColorSchemes.none, "None (No Colors)")
262
test_color_scheme(ColorSchemes.common, "Common")
263
test_color_scheme(ColorSchemes.synthwave, "Synthwave")
264
test_color_scheme(ColorSchemes.nice, "Nice")
265
```
266
267
### Advanced ANSI Color Utilities
268
269
```python
270
from traceback_with_variables.color import to_ansi
271
272
# Create ANSI color codes manually
273
def create_gradient_scheme():
274
"""Create a color scheme with gradient-like colors."""
275
return ColorScheme(
276
common=to_ansi('38;2;200;200;200'), # Light gray
277
file_=to_ansi('38;2;100;150;255'), # Light blue
278
line_num=to_ansi('38;2;255;200;100'), # Light orange
279
func_name=to_ansi('38;2;255;100;150'), # Pink
280
func_snippet=to_ansi('38;2;150;255;150'), # Light green
281
name=to_ansi('38;2;200;100;255'), # Purple
282
value=to_ansi('38;2;100;255;200'), # Cyan
283
exc_class=to_ansi('38;2;255;100;100'), # Light red
284
exc_text=to_ansi('38;2;255;150;150'), # Lighter red
285
end=to_ansi('0') # Reset
286
)
287
288
# Use custom gradient scheme
289
gradient_fmt = Format(color_scheme=create_gradient_scheme())
290
291
try:
292
rgb_data = {"colors": {"red": 255, "green": 128, "blue": 64}}
293
alpha_value = rgb_data["colors"]["alpha"]
294
except Exception as e:
295
print_exc(e, fmt=gradient_fmt)
296
```
297
298
### Platform-Specific Color Configuration
299
300
```python
301
import sys
302
import os
303
from traceback_with_variables import Format, ColorSchemes
304
305
def get_platform_optimized_format():
306
"""Get color format optimized for current platform."""
307
308
if sys.platform == 'win32':
309
# Windows-specific optimizations
310
if 'WT_SESSION' in os.environ:
311
# Windows Terminal supports full colors
312
return Format(color_scheme=ColorSchemes.synthwave)
313
elif os.environ.get('TERM_PROGRAM') == 'vscode':
314
# VS Code on Windows
315
return Format(color_scheme=ColorSchemes.nice)
316
else:
317
# Legacy Windows console
318
return Format(color_scheme=ColorSchemes.common)
319
320
elif sys.platform == 'darwin':
321
# macOS optimizations
322
if os.environ.get('TERM_PROGRAM') == 'Apple_Terminal':
323
return Format(color_scheme=ColorSchemes.nice)
324
elif os.environ.get('TERM_PROGRAM') == 'iTerm.app':
325
return Format(color_scheme=ColorSchemes.synthwave)
326
else:
327
return Format(color_scheme=ColorSchemes.common)
328
329
else:
330
# Linux and other Unix-like systems
331
term = os.environ.get('TERM', '')
332
if 'xterm-256color' in term or 'screen-256color' in term:
333
return Format(color_scheme=ColorSchemes.synthwave)
334
else:
335
return Format(color_scheme=ColorSchemes.common)
336
337
# Use platform-optimized formatting
338
platform_fmt = get_platform_optimized_format()
339
340
try:
341
system_info = {
342
"platform": sys.platform,
343
"terminal": os.environ.get('TERM', 'unknown')
344
}
345
feature = system_info["graphics"]["acceleration"]
346
except Exception as e:
347
print_exc(e, fmt=platform_fmt)
348
```