CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-awscli

Universal Command Line Environment for AWS.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

output-formatting.mddocs/

Output Formatting

Flexible output formatting system supporting multiple formats (JSON, table, text, YAML) with customizable formatters and styling options. The formatting system transforms AWS service responses into user-friendly output formats.

Capabilities

Formatter Selection

Core function for selecting appropriate output formatter based on format and options.

def get_formatter(output_format, args):
    """
    Get appropriate formatter for specified output format.
    
    Parameters:
        output_format: str, output format ('json', 'table', 'text', 'yaml')
        args: parsed arguments with formatting options
        
    Returns:
        Formatter instance for the specified format
    """

def is_response_paginated(response) -> bool:
    """
    Check if response contains paginated results.
    
    Parameters:
        response: AWS service response
        
    Returns:
        bool: True if response is paginated
    """

Base Formatter

Foundation class for all output formatters with common functionality.

class Formatter:
    """
    Base formatter class for all output formats.
    Provides common functionality for formatting AWS service responses.
    """
    
    def __init__(self, args):
        """
        Initialize formatter with command arguments.
        
        Parameters:
            args: parsed command arguments containing formatting options
        """
    
    def __call__(self, data):
        """
        Format data for output. Must be implemented by subclasses.
        
        Parameters:
            data: structured data from AWS service response
        """
    
    def _remove_request_id(self, data):
        """
        Remove request ID from response for cleaner output.
        
        Parameters:
            data: response data that may contain request ID
            
        Returns:
            data with request ID removed
        """
    
    def _get_default_stream(self):
        """
        Get default output stream (stdout).
        
        Returns:
            file-like object for output
        """
    
    def _flush_stream(self, stream=None):
        """
        Flush output stream.
        
        Parameters:
            stream: optional stream to flush, defaults to stdout
        """

Table Formatting

Specialized formatters for tabular output with styling and customization options.

class TableFormatter(Formatter):
    """
    Formatter for table output format.
    Converts structured data into formatted tables.
    """
    
    def __init__(self, args):
        """
        Initialize table formatter.
        
        Parameters:
            args: parsed command arguments with table-specific options
        """
    
    def __call__(self, data):
        """
        Format data as table output.
        
        Parameters:
            data: structured data to format as table
        """

class MultiTable:
    """
    Formatter for multiple related tables.
    Handles complex data structures with nested tables.
    """
    
    def __init__(self, initial_section=True, subsequent_section=False):
        """
        Initialize multi-table formatter.
        
        Parameters:
            initial_section: bool, whether this is the initial table section
            subsequent_section: bool, whether this is a subsequent section
        """
    
    def add_row_header(self, header):
        """
        Add row header to the table.
        
        Parameters:
            header: str, header text for the row
        """
    
    def add_rows(self, rows):
        """
        Add multiple rows to the table.
        
        Parameters:
            rows: list of row data
        """

class Styler:
    """
    Interface for table styling.
    Defines how table elements are styled and colored.
    """
    
    def style_header(self, header):
        """
        Style table header.
        
        Parameters:
            header: str, header text to style
            
        Returns:
            str: styled header text
        """
    
    def style_row(self, row, row_index):
        """
        Style table row.
        
        Parameters:
            row: row data to style
            row_index: int, index of the row
            
        Returns:
            styled row data
        """

class ColorizedStyler(Styler):
    """
    Colorized table styling implementation.
    Adds colors and visual enhancements to table output.
    """
    
    def __init__(self):
        """Initialize colorized styler with ANSI color codes."""
    
    def style_header(self, header):
        """
        Style table header with colors.
        
        Parameters:
            header: str, header text to style
            
        Returns:
            str: colorized header text
        """
    
    def style_row(self, row, row_index):
        """
        Style table row with conditional colors.
        
        Parameters:
            row: row data to style
            row_index: int, index of the row
            
        Returns:
            styled row data with appropriate colors
        """

Format-Specific Formatters

Specialized formatters for different output formats.

class JSONFormatter(Formatter):
    """
    Formatter for JSON output format.
    Converts structured data into JSON format with proper indentation and encoding.
    """
    
    def __init__(self, args):
        """
        Initialize JSON formatter.
        
        Parameters:
            args: parsed command arguments with JSON-specific options
        """
    
    def __call__(self, data):
        """
        Format data as JSON output.
        
        Parameters:
            data: structured data to format as JSON
        """
    
    def _encode_json(self, data):
        """
        Encode data as JSON with proper formatting.
        
        Parameters:
            data: data to encode
            
        Returns:
            str: JSON-encoded string
        """

class TextFormatter(Formatter):
    """
    Formatter for text output format.
    Converts structured data into tab-separated text format for scripting.
    """
    
    def __init__(self, args):
        """
        Initialize text formatter.
        
        Parameters:
            args: parsed command arguments with text-specific options
        """
    
    def __call__(self, data):
        """
        Format data as text output.
        
        Parameters:
            data: structured data to format as text
        """
    
    def _flatten_data(self, data, prefix=""):
        """
        Flatten nested data structure for text output.
        
        Parameters:
            data: nested data structure
            prefix: str, prefix for flattened keys
            
        Returns:
            generator: flattened key-value pairs
        """

class YAMLFormatter(Formatter):
    """
    Formatter for YAML output format.
    Converts structured data into YAML format with proper indentation.
    """
    
    def __init__(self, args):
        """
        Initialize YAML formatter.
        
        Parameters:
            args: parsed command arguments with YAML-specific options
        """
    
    def __call__(self, data):
        """
        Format data as YAML output.
        
        Parameters:
            data: structured data to format as YAML
        """
    
    def _encode_yaml(self, data):
        """
        Encode data as YAML with proper formatting.
        
        Parameters:
            data: data to encode
            
        Returns:
            str: YAML-encoded string
        """

Usage Examples:

from awscli.formatter import get_formatter, JSONFormatter, TextFormatter, YAMLFormatter

# Sample data for formatting examples
data = {
    'Instances': [
        {'InstanceId': 'i-1234567890abcdef0', 'State': {'Name': 'running'}},
        {'InstanceId': 'i-0987654321fedcba0', 'State': {'Name': 'stopped'}}
    ]
}

# Table formatter
table_formatter = get_formatter('table', args)
table_formatter(data)
# Output:
# ---------------------  ---------
# |      InstanceId    |  State  |
# ---------------------  ---------
# |  i-1234567890abc...|  running|
# |  i-0987654321fed...|  stopped|
# ---------------------  ---------

# JSON formatter  
json_formatter = get_formatter('json', args)
json_formatter(data)
# Output: JSON with proper indentation

# Text formatter
text_formatter = get_formatter('text', args)
text_formatter(data)
# Output:
# INSTANCES	i-1234567890abcdef0	running
# INSTANCES	i-0987654321fedcba0	stopped

# YAML formatter
yaml_formatter = get_formatter('yaml', args)
yaml_formatter(data)
# Output: YAML formatted structure

# Direct formatter instantiation
json_formatter = JSONFormatter(args)
json_formatter(data)

text_formatter = TextFormatter(args)
text_formatter(data)

yaml_formatter = YAMLFormatter(args)
yaml_formatter(data)

Output Format Support

JSON Format

Default format providing complete structured output:

# JSON output (default)
{
    "Instances": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "State": {
                "Name": "running",
                "Code": 16
            },
            "InstanceType": "t2.micro"
        }
    ]
}

Table Format

Human-readable tabular format:

# Table output
-----------------------------------------
|              InstanceId               |
-----------------------------------------
|  i-1234567890abcdef0                 |
|  i-0987654321fedcba0                 |
-----------------------------------------

Text Format

Plain text format for scripting:

# Text output
INSTANCES	i-1234567890abcdef0	running
INSTANCES	i-0987654321fedcba0	stopped

YAML Format

YAML structured output:

# YAML output
Instances:
- InstanceId: i-1234567890abcdef0
  State:
    Name: running
    Code: 16
- InstanceId: i-0987654321fedcba0
  State:
    Name: stopped
    Code: 80

Advanced Formatting Features

Custom Formatter Development

from awscli.formatter import Formatter

class CustomFormatter(Formatter):
    """Custom formatter for specialized output."""
    
    def __init__(self, args):
        super().__init__(args)
        self.custom_options = self._parse_custom_options(args)
    
    def __call__(self, data):
        """Format data with custom logic."""
        formatted_data = self._transform_data(data)
        self._output_formatted_data(formatted_data)
    
    def _transform_data(self, data):
        """Apply custom transformations to data."""
        # Custom transformation logic
        return data
    
    def _output_formatted_data(self, data):
        """Output formatted data to stream."""
        import json
        print(json.dumps(data, indent=2))

Query and Filtering Integration

# JMESPath query integration
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,State.Name]' --output table

# Results in filtered table output:
-----------------------  ---------
|  i-1234567890abc...  |  running |
|  i-0987654321fed...  |  stopped |
-----------------------  ---------

Pagination Handling

def handle_paginated_response(response, formatter):
    """Handle paginated responses with appropriate formatting."""
    
    if is_response_paginated(response):
        # Stream paginated results
        for page in response:
            formatter(page)
    else:
        # Format single response
        formatter(response)

Color and Styling

class CustomColorizedStyler(ColorizedStyler):
    """Custom colorized styling for tables."""
    
    def style_header(self, header):
        """Style table header with custom colors."""
        return f"\033[1;36m{header}\033[0m"  # Cyan bold
    
    def style_row(self, row, row_index):
        """Style table row based on content."""
        if 'running' in str(row):
            return f"\033[0;32m{row}\033[0m"  # Green
        elif 'stopped' in str(row):
            return f"\033[0;31m{row}\033[0m"  # Red
        return str(row)

Output Format Configuration

Global Format Settings

# Set default output format
aws configure set output json
aws configure set output table
aws configure set output text
aws configure set output yaml

# Per-profile format settings
aws configure set output table --profile development
aws configure set output json --profile production

Command-Specific Formatting

# Override format for specific command
aws ec2 describe-instances --output table
aws s3 ls --output text
aws iam list-users --output yaml

Programmatic Format Control

from awscli.clidriver import create_clidriver

# Create driver with specific output format
driver = create_clidriver()
exit_code = driver.main([
    'ec2', 'describe-instances',
    '--output', 'table',
    '--query', 'Reservations[*].Instances[*].[InstanceId,State.Name]'
])

Integration with Custom Commands

from awscli.customizations.commands import BasicCommand
from awscli.formatter import get_formatter

class CustomOutputCommand(BasicCommand):
    NAME = 'custom-output'
    DESCRIPTION = 'Command demonstrating custom output formatting'
    
    def _run_main(self, parsed_args, parsed_globals):
        # Generate data
        data = self._collect_data()
        
        # Get formatter based on global output setting
        output_format = parsed_globals.get('output', 'json')
        formatter = get_formatter(output_format, parsed_args)
        
        # Format and output data
        formatter(data)
        return 0
    
    def _collect_data(self):
        """Collect data for output."""
        return {
            'CustomData': [
                {'Name': 'Item1', 'Value': 'Value1'},
                {'Name': 'Item2', 'Value': 'Value2'}
            ],
            'Metadata': {
                'Total': 2,
                'Generated': '2024-01-01T00:00:00Z'
            }
        }

Install with Tessl CLI

npx tessl i tessl/pypi-awscli

docs

argument-processing.md

command-system.md

core-driver.md

custom-commands.md

error-handling.md

help-system.md

index.md

output-formatting.md

plugin-system.md

testing-framework.md

utilities.md

tile.json