CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-textfsm

Python module for parsing semi-structured text into python tables.

Overview
Eval results
Files

text-tables.mddocs/

Text Tables

The TextTable module provides tabular data representation and formatting capabilities for displaying parsed results as structured tables with various output formats including CSV, formatted text, and HTML.

Core Imports

from textfsm import texttable
from textfsm.texttable import TextTable, Row
from textfsm.texttable import TableError

Capabilities

TextTable Class

Main table class for storing, manipulating, and formatting tabular data with support for multiple display formats.

class TextTable(object):
    def __init__(self, row_class=Row):
        """
        Initialize text table.
        
        Args:
            row_class: Row class to use for table rows (default: Row)
        """
    
    def Append(self, row_data):
        """
        Add row to table.
        
        Args:
            row_data (list): List of values for the row
        """
    
    def extend(self, table, keys=None):
        """
        Add multiple rows from another table.
        
        Args:
            table: TextTable or list of rows to extend with
            keys (list): Specific keys/columns to copy (optional)
        """
    
    def CsvToTable(self, buf, header=True, separator=','):
        """
        Populate table from CSV data.
        
        Args:
            buf: CSV data as string or file-like object
            header (bool): True if first row contains headers
            separator (str): Field separator character
            
        Returns:
            int: Number of rows processed
        """
    
    def LabelValueTable(self, data):
        """
        Create label-value formatted table display.
        
        Args:
            data: Data to format as label-value pairs
            
        Returns:
            str: Formatted label-value representation
        """
    
    def FormattedTable(self, width=80, force_display=False, ml_delimiter=True, color=True, display_header=True, columns=None):
        """
        Get formatted table as string.
        
        Args:
            width (int): Maximum width for table formatting
            force_display (bool): Force display even if table is empty
            ml_delimiter (bool): Use multi-line delimiter
            color (bool): Include color formatting
            display_header (bool): Show column headers
            columns (list): Specific columns to display
            
        Returns:
            str: Formatted table with borders and alignment
        """
    
    def NewRow(self, value=''):
        """
        Create new empty row.
        
        Args:
            value: Default value for row cells
            
        Returns:
            Row: Empty row object
        """
    
    def Reset(self):
        """Clear all table data and headers."""
    
    def Remove(self, row):
        """
        Remove row from table.
        
        Args:
            row: Row object to remove
        """
    
    def sort(self, cmp=None, key=None, reverse=False):
        """
        Sort table rows.
        
        Args:
            cmp: Comparison function (deprecated)
            key: Key function for sorting
            reverse (bool): Sort in reverse order
        """
    
    def Filter(self, function=None):
        """
        Filter table rows using a function.
        
        Args:
            function (callable): Function to test each row
            
        Returns:
            TextTable: New table with filtered rows
        """
    
    def Map(self, function):
        """
        Apply function to each row in table.
        
        Args:
            function (callable): Function to apply to each row
            
        Returns:
            TextTable: New table with transformed rows
        """
    
    def RowWith(self, column, value):
        """
        Find first row with specific column value.
        
        Args:
            column (str): Column name to search
            value: Value to match
            
        Returns:
            Row: First matching row, or None if not found
        """
    
    def index(self, name=None):
        """
        Get column index by name.
        
        Args:
            name (str): Column name to find
            
        Returns:
            int: Column index
        """
    
    def AddColumn(self, column, default='', col_index=-1):
        """
        Add column to table.
        
        Args:
            column (str): Column name
            default: Default value for existing rows
            col_index (int): Position to insert column (-1 for end)
        """
    
    def __repr__(self):
        """String representation of table."""
    
    def __str__(self):
        """Formatted string representation."""
    
    def __iter__(self):
        """Iterate over table rows."""
    
    def __next__(self):
        """Get next row in iteration."""
    
    def __getitem__(self, row):
        """Get row by index."""
    
    def __contains__(self, name):
        """Check if column name exists."""
    
    def __add__(self, other):
        """Concatenate tables."""
    
    def __copy__(self):
        """Create shallow copy."""
    
    @property
    def header(self):
        """List of column headers."""
    
    @property
    def table(self):
        """List of Row objects."""
    
    @property
    def row(self):
        """Current row object."""
    
    @property
    def row_index(self):
        """Current row index."""
    
    @property
    def size(self):
        """Number of rows in table."""
    
    @property
    def separator(self):
        """Field separator character."""
    
    @property
    def row_class(self):
        """Row class used for creating rows."""

Row Class

Represents individual table rows as ordered dictionaries with table context and formatting capabilities.

class Row(dict):
    def __init__(self, *args, **kwargs):
        """
        Initialize table row.
        
        Args:
            *args: Arguments passed to dict constructor
            **kwargs: Keyword arguments passed to dict constructor
        """
    
    def __getitem__(self, column):
        """Get value by column name or index."""
    
    def __setitem__(self, column, value):
        """Set value by column name or index."""
    
    def __contains__(self, value):
        """Check if value exists in row."""
    
    def __iter__(self):
        """Iterate over row values."""
    
    def __len__(self):
        """Get number of columns in row."""
    
    def __str__(self):
        """String representation of row."""
    
    def __repr__(self):
        """Debug representation of row."""
    
    def get(self, column, default_value=None):
        """
        Get value from column with default.
        
        Args:
            column: Column name or index
            default_value: Default value if column not found
            
        Returns:
            Value from column or default
        """
    
    def index(self, column):
        """
        Get index of column.
        
        Args:
            column: Column name
            
        Returns:
            int: Column index
        """
    
    def iterkeys(self):
        """
        Iterate over column names.
        
        Returns:
            Iterator: Column name iterator
        """
    
    def items(self):
        """
        Get column name-value pairs.
        
        Returns:
            list: List of (name, value) tuples
        """
    
    def Insert(self, key, value, row_index):
        """
        Insert value at specific position.
        
        Args:
            key: Column name
            value: Value to insert
            row_index (int): Position to insert at
        """
    
    @property
    def header(self):
        """List of column headers from parent table."""
    
    @property
    def header(self):
        """List of column headers from parent table."""
    
    @property
    def values(self):
        """List of row values in column order."""
    
    @property
    def row(self):
        """Row values as list."""
    
    @property
    def table(self):
        """Parent TextTable instance."""
    
    @property
    def color(self):
        """Row color specification."""

Usage Examples

Basic Table Operations

from textfsm import texttable

# Create table with headers
table = texttable.TextTable(['Name', 'Age', 'City'])

# Add rows
table.Append(['Alice', '25', 'New York'])
table.Append(['Bob', '30', 'San Francisco'])
table.Append(['Charlie', '35', 'Chicago'])

# Display formatted table
print(table.FormattedTable())

Working with CSV Data

from textfsm import texttable

# Create table from CSV
csv_data = """Name,Age,City
Alice,25,New York
Bob,30,San Francisco
Charlie,35,Chicago"""

table = texttable.TextTable()
table.CsvToTable(csv_data)

# Convert back to CSV
csv_output = table.TableToCSV()
print(csv_output)

Label-Value Format Processing

from textfsm import texttable

# Parse label-value formatted data
data = """
Name: Alice
Age: 25
City: New York
---
Name: Bob
Age: 30
City: San Francisco
"""

table = texttable.TextTable()
table.LabelValueTable(data, separator=':', skip_line=lambda x: x.startswith('---'))

Row Manipulation

from textfsm import texttable

table = texttable.TextTable(['Name', 'Score'])

# Create and populate rows
row1 = table.NewRow()
row1.AssignVar('Name', 'Alice')
row1.AssignVar('Score', '95')
table.Append(row1.row())

# Access row data
for row in table.table:
    name = row.GetVar('Name')
    score = row.GetVar('Score')
    print(f"{name}: {score}")

Table Sorting and Filtering

from textfsm import texttable

table = texttable.TextTable(['Name', 'Score', 'Grade'])
table.Append(['Alice', '95', 'A'])
table.Append(['Bob', '87', 'B'])
table.Append(['Charlie', '92', 'A'])

# Sort by score (descending)
table.sort(['Score'])

# Filter rows (example would require actual implementation)
# table.Filter(lambda row: int(row.GetVar('Score')) > 90)

# Add new column
table.AddColumn('Pass', ['Yes', 'Yes', 'Yes'])

Integration with TextFSM

import io
import textfsm
from textfsm import texttable

# Parse with TextFSM
template = """
Value NAME (\S+)
Value SCORE (\d+)

Start
  ^${NAME} scored ${SCORE} points -> Record
"""

text = "Alice scored 95 points\nBob scored 87 points"
fsm = textfsm.TextFSM(io.StringIO(template))
results = fsm.ParseText(text)

# Create formatted table
table = texttable.TextTable(fsm.header)
table.extend(results)
print(table.FormattedTable())

Custom Formatting

from textfsm import texttable

table = texttable.TextTable(['Product', 'Price', 'Stock'])
table.Append(['Widget A', '$19.99', '150'])
table.Append(['Widget B', '$29.99', '75'])

# Get formatted output with custom options
formatted = table.FormattedTable()
print(formatted)

# Export to different formats
csv_data = table.TableToCSV()

Install with Tessl CLI

npx tessl i tessl/pypi-textfsm

docs

cli-tables.md

core-parser.md

index.md

terminal-utils.md

text-tables.md

tile.json