Python module for parsing semi-structured text into python tables.
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.
from textfsm import terminal
from textfsm.terminal import AnsiText, StripAnsiText, Pager
from textfsm.terminal import Error, UsageErrorFunctions for creating colored and styled terminal output using ANSI escape sequences.
def AnsiText(text, command_list=None, reset=True):
"""
Create ANSI formatted text with color and style.
Args:
text (str): Text to format
command_list (list): List of SGR command strings (e.g., ['fg_red', 'bold'])
reset (bool): Whether to add reset sequence at end (default: True)
Returns:
str: Text wrapped with ANSI escape sequences
"""
def StripAnsiText(text):
"""
Remove ANSI escape sequences from text.
Args:
text (str): Text containing ANSI sequences
Returns:
str: Plain text with ANSI sequences removed
"""
def EncloseAnsiText(text):
"""
Wrap text with ANSI formatting while preserving existing formatting.
Args:
text (str): Text to wrap
Returns:
str: Text with additional ANSI formatting
"""
def LineWrap(text, omit_sgr=False):
"""
Wrap text lines to specified width with ANSI handling.
Args:
text (str): Text to wrap
omit_sgr (bool): Whether to omit SGR sequences in width calculation
Returns:
str: Wrapped text
"""Interactive text pager for displaying large amounts of text with scrolling capabilities.
class Pager(object):
def __init__(self, text='', delay=False):
"""
Initialize text pager.
Args:
text (str): Initial text to page
delay (bool): Whether to delay display
"""
def Reset(self):
"""Reset pager state."""
def SetLines(self, num_lines=0):
"""
Set terminal size.
Args:
num_lines (int): Number of lines (0 for auto-detect)
Returns:
tuple: (lines, columns) terminal dimensions
"""
def Clear(self):
"""Clear terminal screen."""
def Page(self, more_text=''):
"""
Page through text content.
Args:
more_text (str): Additional text to append
"""
@property
def first_line(self):
"""First line number being displayed."""Pre-defined constants and mappings for terminal control and color formatting.
# ANSI SGR (Select Graphic Rendition) codes
SGR = {
'reset': 0,
'bold': 1,
'underline': 4,
'blink': 5,
'negative': 7,
'black': 30,
'red': 31,
'green': 32,
'yellow': 33,
'blue': 34,
'magenta': 35,
'cyan': 36,
'white': 37,
'bg_black': 40,
'bg_red': 41,
'bg_green': 42,
'bg_yellow': 43,
'bg_blue': 44,
'bg_magenta': 45,
'bg_cyan': 46,
'bg_white': 47
}
# ANSI escape sequence delimiters
ANSI_START = '\033['
ANSI_END = 'm'
# Terminal control sequences
CLEAR_SCREEN = '\033[2J\033[H'
UP_ARROW = '\033[A'
DOWN_ARROW = '\033[B'
# Color name mappings
FG_COLOR_WORDS = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
BG_COLOR_WORDS = ['bg_black', 'bg_red', 'bg_green', 'bg_yellow', 'bg_blue', 'bg_magenta', 'bg_cyan', 'bg_white']
# Prompt character
PROMPT_QUESTION = '? '
# Compiled regex for ANSI sequences
import re
sgr_re = re.compile(r'\x1b\[[0-9;]*m')def _AnsiCmd(command_list):
"""
Create ANSI command sequence from command list.
Args:
command_list (list): List of ANSI command strings
Returns:
str: ANSI escape sequence
"""
def _GetChar():
"""
Get single character input from terminal.
Returns:
str: Single character
"""
def _PosixGetChar():
"""
Get character on POSIX systems.
Returns:
str: Single character
"""
def _MSGetChar():
"""
Get character on Windows systems.
Returns:
str: Single character
"""class Error(Exception):
"""Base exception class for terminal module."""
class UsageError(Error):
"""Command line format error."""def main(argv=None):
"""
Command-line interface for terminal operations.
Args:
argv (list): Command line arguments (default: sys.argv)
Returns:
int: Exit code (0 for success)
"""from textfsm import terminal
# Colored text
red_text = terminal.AnsiText("Error message", ['red', 'bold'])
green_text = terminal.AnsiText("Success", ['green'])
blue_bg = terminal.AnsiText("Highlighted", ['bg_blue'])
print(red_text)
print(green_text)
print(blue_bg)
# Multiple formatting options
formatted = terminal.AnsiText("Important notice",
['yellow', 'bg_red', 'bold', 'underline'])
print(formatted)from textfsm import terminal
# Remove ANSI formatting from text
colored_text = terminal.AnsiText("Colored text", fg='red')
plain_text = terminal.StripAnsiText(colored_text)
print(f"Colored: {colored_text}")
print(f"Plain: {plain_text}")
# Wrap long lines
long_text = "This is a very long line of text that needs to be wrapped to fit within terminal width constraints."
wrapped = terminal.LineWrap(long_text, width=40, indent=4, subsequent_indent=8)
print(wrapped)from textfsm import terminal
# Create pager instance
pager = terminal.Pager()
# Display large text content
large_text = "\n".join([f"Line {i}: Some content here" for i in range(100)])
pager.Page(large_text)
# Use specific pager command
pager = terminal.Pager('less -R') # less with raw control characters
pager.Page(terminal.AnsiText("Colored text in pager", fg='green'))from textfsm import terminal
# Direct use of SGR codes
print(f"{terminal.ANSI_START}{terminal.SGR['red']}{terminal.ANSI_END}Red text{terminal.ANSI_START}{terminal.SGR['reset']}{terminal.ANSI_END}")
# Check available colors
print("Foreground colors:", terminal.FG_COLOR_WORDS)
print("Background colors:", terminal.BG_COLOR_WORDS)
# Clear screen
print(terminal.CLEAR_SCREEN)from textfsm import terminal
def create_header(text):
"""Create a formatted header."""
return terminal.AnsiText(f"=== {text} ===", ['blue', 'bold'])
def create_error(text):
"""Create formatted error message."""
return terminal.AnsiText(f"ERROR: {text}", ['red', 'bg_white', 'bold'])
def create_success(text):
"""Create formatted success message."""
return terminal.AnsiText(f"✓ {text}", ['green', 'bold'])
# Usage
print(create_header("System Status"))
print(create_success("Database connection established"))
print(create_error("Failed to load configuration"))import io
import textfsm
from textfsm import terminal
# Parse data with TextFSM
template = """
Value DEVICE (\S+)
Value STATUS (up|down)
Value UPTIME (.+)
Start
^${DEVICE} is ${STATUS}, uptime: ${UPTIME} -> Record
"""
text = """
router1 is up, uptime: 5 days, 2 hours
router2 is down, uptime: 0 minutes
router3 is up, uptime: 15 days, 8 hours
"""
fsm = textfsm.TextFSM(io.StringIO(template))
results = fsm.ParseText(text)
# Format output with colors
print(create_header("Network Device Status"))
for device, status, uptime in results:
if status == 'up':
status_text = terminal.AnsiText(status.upper(), ['green', 'bold'])
else:
status_text = terminal.AnsiText(status.upper(), ['red', 'bold'])
print(f"{device:10} {status_text} {uptime}")Install with Tessl CLI
npx tessl i tessl/pypi-textfsm