0
# Terminal Utilities
1
2
The terminal module provides ANSI text formatting, terminal control, and paging functionality for enhanced command-line output display. It includes utilities for colored text, text wrapping, and interactive paging of large text outputs.
3
4
## Core Imports
5
6
```python
7
from textfsm import terminal
8
from textfsm.terminal import AnsiText, StripAnsiText, Pager
9
from textfsm.terminal import Error, UsageError
10
```
11
12
## Capabilities
13
14
### ANSI Text Formatting
15
16
Functions for creating colored and styled terminal output using ANSI escape sequences.
17
18
```python { .api }
19
def AnsiText(text, command_list=None, reset=True):
20
"""
21
Create ANSI formatted text with color and style.
22
23
Args:
24
text (str): Text to format
25
command_list (list): List of SGR command strings (e.g., ['fg_red', 'bold'])
26
reset (bool): Whether to add reset sequence at end (default: True)
27
28
Returns:
29
str: Text wrapped with ANSI escape sequences
30
"""
31
32
def StripAnsiText(text):
33
"""
34
Remove ANSI escape sequences from text.
35
36
Args:
37
text (str): Text containing ANSI sequences
38
39
Returns:
40
str: Plain text with ANSI sequences removed
41
"""
42
43
def EncloseAnsiText(text):
44
"""
45
Wrap text with ANSI formatting while preserving existing formatting.
46
47
Args:
48
text (str): Text to wrap
49
50
Returns:
51
str: Text with additional ANSI formatting
52
"""
53
54
def LineWrap(text, omit_sgr=False):
55
"""
56
Wrap text lines to specified width with ANSI handling.
57
58
Args:
59
text (str): Text to wrap
60
omit_sgr (bool): Whether to omit SGR sequences in width calculation
61
62
Returns:
63
str: Wrapped text
64
"""
65
```
66
67
### Pager Class
68
69
Interactive text pager for displaying large amounts of text with scrolling capabilities.
70
71
```python { .api }
72
class Pager(object):
73
def __init__(self, text='', delay=False):
74
"""
75
Initialize text pager.
76
77
Args:
78
text (str): Initial text to page
79
delay (bool): Whether to delay display
80
"""
81
82
def Reset(self):
83
"""Reset pager state."""
84
85
def SetLines(self, num_lines=0):
86
"""
87
Set terminal size.
88
89
Args:
90
num_lines (int): Number of lines (0 for auto-detect)
91
92
Returns:
93
tuple: (lines, columns) terminal dimensions
94
"""
95
96
def Clear(self):
97
"""Clear terminal screen."""
98
99
def Page(self, more_text=''):
100
"""
101
Page through text content.
102
103
Args:
104
more_text (str): Additional text to append
105
"""
106
107
@property
108
def first_line(self):
109
"""First line number being displayed."""
110
```
111
112
### Terminal Control Constants
113
114
Pre-defined constants and mappings for terminal control and color formatting.
115
116
```python { .api }
117
# ANSI SGR (Select Graphic Rendition) codes
118
SGR = {
119
'reset': 0,
120
'bold': 1,
121
'underline': 4,
122
'blink': 5,
123
'negative': 7,
124
'black': 30,
125
'red': 31,
126
'green': 32,
127
'yellow': 33,
128
'blue': 34,
129
'magenta': 35,
130
'cyan': 36,
131
'white': 37,
132
'bg_black': 40,
133
'bg_red': 41,
134
'bg_green': 42,
135
'bg_yellow': 43,
136
'bg_blue': 44,
137
'bg_magenta': 45,
138
'bg_cyan': 46,
139
'bg_white': 47
140
}
141
142
# ANSI escape sequence delimiters
143
ANSI_START = '\033['
144
ANSI_END = 'm'
145
146
# Terminal control sequences
147
CLEAR_SCREEN = '\033[2J\033[H'
148
UP_ARROW = '\033[A'
149
DOWN_ARROW = '\033[B'
150
151
# Color name mappings
152
FG_COLOR_WORDS = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
153
BG_COLOR_WORDS = ['bg_black', 'bg_red', 'bg_green', 'bg_yellow', 'bg_blue', 'bg_magenta', 'bg_cyan', 'bg_white']
154
155
# Prompt character
156
PROMPT_QUESTION = '? '
157
158
# Compiled regex for ANSI sequences
159
import re
160
sgr_re = re.compile(r'\x1b\[[0-9;]*m')
161
```
162
163
### Internal Functions
164
165
```python { .api }
166
def _AnsiCmd(command_list):
167
"""
168
Create ANSI command sequence from command list.
169
170
Args:
171
command_list (list): List of ANSI command strings
172
173
Returns:
174
str: ANSI escape sequence
175
"""
176
177
def _GetChar():
178
"""
179
Get single character input from terminal.
180
181
Returns:
182
str: Single character
183
"""
184
185
def _PosixGetChar():
186
"""
187
Get character on POSIX systems.
188
189
Returns:
190
str: Single character
191
"""
192
193
def _MSGetChar():
194
"""
195
Get character on Windows systems.
196
197
Returns:
198
str: Single character
199
"""
200
```
201
202
### Exception Classes
203
204
```python { .api }
205
class Error(Exception):
206
"""Base exception class for terminal module."""
207
208
class UsageError(Error):
209
"""Command line format error."""
210
```
211
212
### Command Line Interface
213
214
```python { .api }
215
def main(argv=None):
216
"""
217
Command-line interface for terminal operations.
218
219
Args:
220
argv (list): Command line arguments (default: sys.argv)
221
222
Returns:
223
int: Exit code (0 for success)
224
"""
225
```
226
227
## Usage Examples
228
229
### Basic Text Formatting
230
231
```python
232
from textfsm import terminal
233
234
# Colored text
235
red_text = terminal.AnsiText("Error message", ['red', 'bold'])
236
green_text = terminal.AnsiText("Success", ['green'])
237
blue_bg = terminal.AnsiText("Highlighted", ['bg_blue'])
238
239
print(red_text)
240
print(green_text)
241
print(blue_bg)
242
243
# Multiple formatting options
244
formatted = terminal.AnsiText("Important notice",
245
['yellow', 'bg_red', 'bold', 'underline'])
246
print(formatted)
247
```
248
249
### Text Processing
250
251
```python
252
from textfsm import terminal
253
254
# Remove ANSI formatting from text
255
colored_text = terminal.AnsiText("Colored text", fg='red')
256
plain_text = terminal.StripAnsiText(colored_text)
257
print(f"Colored: {colored_text}")
258
print(f"Plain: {plain_text}")
259
260
# Wrap long lines
261
long_text = "This is a very long line of text that needs to be wrapped to fit within terminal width constraints."
262
wrapped = terminal.LineWrap(long_text, width=40, indent=4, subsequent_indent=8)
263
print(wrapped)
264
```
265
266
### Using the Pager
267
268
```python
269
from textfsm import terminal
270
271
# Create pager instance
272
pager = terminal.Pager()
273
274
# Display large text content
275
large_text = "\n".join([f"Line {i}: Some content here" for i in range(100)])
276
pager.Page(large_text)
277
278
# Use specific pager command
279
pager = terminal.Pager('less -R') # less with raw control characters
280
pager.Page(terminal.AnsiText("Colored text in pager", fg='green'))
281
```
282
283
### Working with SGR Codes
284
285
```python
286
from textfsm import terminal
287
288
# Direct use of SGR codes
289
print(f"{terminal.ANSI_START}{terminal.SGR['red']}{terminal.ANSI_END}Red text{terminal.ANSI_START}{terminal.SGR['reset']}{terminal.ANSI_END}")
290
291
# Check available colors
292
print("Foreground colors:", terminal.FG_COLOR_WORDS)
293
print("Background colors:", terminal.BG_COLOR_WORDS)
294
295
# Clear screen
296
print(terminal.CLEAR_SCREEN)
297
```
298
299
### Custom Text Styling
300
301
```python
302
from textfsm import terminal
303
304
def create_header(text):
305
"""Create a formatted header."""
306
return terminal.AnsiText(f"=== {text} ===", ['blue', 'bold'])
307
308
def create_error(text):
309
"""Create formatted error message."""
310
return terminal.AnsiText(f"ERROR: {text}", ['red', 'bg_white', 'bold'])
311
312
def create_success(text):
313
"""Create formatted success message."""
314
return terminal.AnsiText(f"✓ {text}", ['green', 'bold'])
315
316
# Usage
317
print(create_header("System Status"))
318
print(create_success("Database connection established"))
319
print(create_error("Failed to load configuration"))
320
```
321
322
### Integration with TextFSM Output
323
324
```python
325
import io
326
import textfsm
327
from textfsm import terminal
328
329
# Parse data with TextFSM
330
template = """
331
Value DEVICE (\S+)
332
Value STATUS (up|down)
333
Value UPTIME (.+)
334
335
Start
336
^${DEVICE} is ${STATUS}, uptime: ${UPTIME} -> Record
337
"""
338
339
text = """
340
router1 is up, uptime: 5 days, 2 hours
341
router2 is down, uptime: 0 minutes
342
router3 is up, uptime: 15 days, 8 hours
343
"""
344
345
fsm = textfsm.TextFSM(io.StringIO(template))
346
results = fsm.ParseText(text)
347
348
# Format output with colors
349
print(create_header("Network Device Status"))
350
for device, status, uptime in results:
351
if status == 'up':
352
status_text = terminal.AnsiText(status.upper(), ['green', 'bold'])
353
else:
354
status_text = terminal.AnsiText(status.upper(), ['red', 'bold'])
355
356
print(f"{device:10} {status_text} {uptime}")
357
```