CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-typer

Typer, build great CLIs. Easy to code. Based on Python type hints.

Overview
Eval results
Files

terminal-utilities.mddocs/

Terminal Utilities

Re-exported Click functions for terminal interaction, styling, and user input/output operations. These utilities provide cross-platform terminal functionality for CLI applications.

Capabilities

Output Functions

Functions for displaying text and information to the terminal with various formatting options.

def echo(message: Optional[str] = None, file=None, nl: bool = True, err: bool = False, color: Optional[bool] = None):
    """
    Print a message to stdout or stderr.

    Parameters:
    - message: Text to print
    - file: File object to write to (default: stdout)
    - nl: Add newline at the end
    - err: Write to stderr instead of stdout
    - color: Force enable/disable colors

    Example:
    ```python
    typer.echo("Hello World!")
    typer.echo("Error occurred", err=True)
    ```
    """

def secho(message: Optional[str] = None, file=None, nl: bool = True, err: bool = False, color: Optional[bool] = None, **styles):
    """
    Print a styled message to stdout or stderr.

    Parameters:
    - message: Text to print
    - file: File object to write to
    - nl: Add newline at the end
    - err: Write to stderr instead of stdout
    - color: Force enable/disable colors
    - styles: Style keywords (fg, bg, bold, dim, underline, blink, reverse, reset)

    Example:
    ```python
    typer.secho("Success!", fg="green", bold=True)
    typer.secho("Warning!", fg="yellow")
    typer.secho("Error!", fg="red", err=True)
    ```
    """

def style(text: str, fg=None, bg=None, bold: Optional[bool] = None, dim: Optional[bool] = None, underline: Optional[bool] = None, blink: Optional[bool] = None, reverse: Optional[bool] = None, reset: bool = True) -> str:
    """
    Apply styling to text and return styled string.

    Parameters:
    - text: Text to style
    - fg: Foreground color
    - bg: Background color
    - bold: Bold text
    - dim: Dim text
    - underline: Underlined text
    - blink: Blinking text
    - reverse: Reverse video
    - reset: Reset styles after text

    Returns:
    Styled text string

    Example:
    ```python
    styled = typer.style("Important", fg="red", bold=True)
    typer.echo(styled)
    ```
    """

def unstyle(text: str) -> str:
    """
    Remove all ANSI styling from text.

    Parameters:
    - text: Text with ANSI codes

    Returns:
    Plain text without styling

    Example:
    ```python
    plain = typer.unstyle("\x1b[31mRed text\x1b[0m")
    # plain == "Red text"
    ```
    """

User Input Functions

Functions for prompting users for input with various validation and formatting options.

def prompt(text: str, default=None, hide_input: bool = False, confirmation_prompt: bool = False, type=None, value_proc=None, prompt_suffix: str = ": ", show_default: bool = True, err: bool = False, show_choices: bool = True) -> Any:
    """
    Prompt user for input.

    Parameters:
    - text: Prompt text to display
    - default: Default value if user enters nothing
    - hide_input: Hide input (for passwords)
    - confirmation_prompt: Ask for confirmation
    - type: Input type (int, float, etc.)
    - value_proc: Function to process the value
    - prompt_suffix: Suffix after prompt text
    - show_default: Show default value in prompt
    - err: Show prompt on stderr
    - show_choices: Show available choices

    Returns:
    User input value

    Example:
    ```python
    name = typer.prompt("Your name")
    age = typer.prompt("Your age", type=int)
    password = typer.prompt("Password", hide_input=True)
    ```
    """

def confirm(text: str, default: bool = False, abort: bool = False, prompt_suffix: str = " [y/N]: ", show_default: bool = True, err: bool = False) -> bool:
    """
    Prompt user for yes/no confirmation.

    Parameters:
    - text: Confirmation text
    - default: Default value (True/False)
    - abort: Raise Abort exception if user says no
    - prompt_suffix: Suffix for the prompt
    - show_default: Show default in prompt
    - err: Show prompt on stderr

    Returns:
    True if user confirms, False otherwise

    Example:
    ```python
    if typer.confirm("Delete all files?"):
        typer.echo("Deleting files...")
    else:
        typer.echo("Aborted.")
    ```
    """

Terminal Control Functions

Functions for controlling terminal display and behavior.

def clear():
    """
    Clear the terminal screen.

    Example:
    ```python
    typer.clear()
    typer.echo("Screen cleared!")
    ```
    """

def pause(info: str = "Press any key to continue..."):
    """
    Pause execution until user presses a key.

    Parameters:
    - info: Message to display

    Example:
    ```python
    typer.echo("Processing complete.")
    typer.pause()
    typer.echo("Continuing...")
    ```
    """

def getchar(echo: bool = False) -> str:
    """
    Get a single character from stdin.

    Parameters:
    - echo: Echo the character to stdout

    Returns:
    Single character string

    Example:
    ```python
    typer.echo("Press any key...")
    char = typer.getchar()
    typer.echo(f"You pressed: {char}")
    ```
    """

Advanced Output Functions

Functions for handling large amounts of text and complex output scenarios.

def echo_via_pager(text_or_generator, color: Optional[bool] = None):
    """
    Echo text through a pager (like 'less' or 'more').

    Parameters:
    - text_or_generator: Text string or generator yielding text
    - color: Enable/disable colors in pager

    Example:
    ```python
    long_text = "\\n".join(f"Line {i}" for i in range(1000))
    typer.echo_via_pager(long_text)
    ```
    """

def edit(text: Optional[str] = None, editor: Optional[str] = None, env: Optional[str] = None, require_save: bool = True, extension: str = ".txt", filename: Optional[str] = None) -> Optional[str]:
    """
    Open text editor for user input.

    Parameters:
    - text: Initial text content
    - editor: Editor command to use
    - env: Environment variable for editor
    - require_save: Require user to save
    - extension: File extension for temp file
    - filename: Specific filename to use

    Returns:
    Edited text or None if not saved

    Example:
    ```python
    edited_text = typer.edit("Initial content")
    if edited_text:
        typer.echo("Text was edited")
    ```
    """

def progressbar(iterable=None, length: Optional[int] = None, label: Optional[str] = None, show_eta: bool = True, show_percent: Optional[bool] = None, show_pos: bool = False, item_show_func=None, fill_char: str = "#", empty_char: str = "-", bar_template: str = "%(label)s  [%(bar)s]  %(info)s", info_sep: str = "  ", width: int = 36, file=None, color: Optional[bool] = None):
    """
    Create a progress bar for iterating over items.

    Parameters:
    - iterable: Items to iterate over
    - length: Total number of items (if iterable doesn't have len())
    - label: Label to show before progress bar
    - show_eta: Show estimated time remaining
    - show_percent: Show percentage complete
    - show_pos: Show current position
    - item_show_func: Function to display current item
    - fill_char: Character for completed portion
    - empty_char: Character for remaining portion
    - bar_template: Template for bar display
    - info_sep: Separator for info sections
    - width: Width of progress bar
    - file: File to write progress to
    - color: Enable/disable colors

    Returns:
    Progress bar context manager

    Example:
    ```python
    import time
    
    items = range(100)
    with typer.progressbar(items, label="Processing") as progress:
        for item in progress:
            time.sleep(0.01)  # Simulate work
    ```
    """

File and System Utilities

Utility functions for file operations and system interaction.

def format_filename(filename: str, shorten: bool = False) -> str:
    """
    Format a filename for display.

    Parameters:
    - filename: Filename to format
    - shorten: Shorten long filenames

    Returns:
    Formatted filename string

    Example:
    ```python
    formatted = typer.format_filename("/very/long/path/to/file.txt", shorten=True)
    typer.echo(f"Processing {formatted}")
    ```
    """

def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:
    """
    Get the application directory for storing data.

    Parameters:
    - app_name: Name of the application
    - roaming: Use roaming directory on Windows
    - force_posix: Force POSIX-style paths

    Returns:
    Application directory path

    Example:
    ```python
    app_dir = typer.get_app_dir("myapp")
    config_file = os.path.join(app_dir, "config.json")
    ```
    """

def get_binary_stream(name: str):
    """
    Get a binary stream (stdin/stdout/stderr).

    Parameters:
    - name: Stream name ("stdin", "stdout", "stderr")

    Returns:
    Binary stream object

    Example:
    ```python
    stdin = typer.get_binary_stream("stdin")
    data = stdin.read()
    ```
    """

def get_text_stream(name: str, encoding: Optional[str] = None, errors: str = "strict"):
    """
    Get a text stream (stdin/stdout/stderr).

    Parameters:
    - name: Stream name ("stdin", "stdout", "stderr")
    - encoding: Text encoding
    - errors: Error handling

    Returns:
    Text stream object

    Example:
    ```python
    stdout = typer.get_text_stream("stdout")
    stdout.write("Hello World!")
    ```
    """

def open_file(filename: str, mode: str = "r", encoding: Optional[str] = None, errors: str = "strict", lazy: bool = False, atomic: bool = False):
    """
    Open a file with proper error handling and atomic operations.

    Parameters:
    - filename: Name of file to open
    - mode: File open mode
    - encoding: Text encoding
    - errors: Error handling
    - lazy: Lazy file opening
    - atomic: Atomic file operations

    Returns:
    File object

    Example:
    ```python
    with typer.open_file("data.txt", "w", atomic=True) as f:
        f.write("Safe atomic write")
    ```
    """

def get_terminal_size() -> os.terminal_size:
    """
    Get the terminal size.

    Returns:
    Terminal size with columns and lines attributes

    Example:
    ```python
    size = typer.get_terminal_size()
    typer.echo(f"Terminal: {size.columns}x{size.lines}")
    ```
    """

Usage Examples

Styled Output

import typer

def show_status():
    """Demonstrate styled output."""
    typer.secho("✓ Success", fg="green", bold=True)
    typer.secho("⚠ Warning", fg="yellow")
    typer.secho("✗ Error", fg="red", err=True)
    
    # Custom styling
    styled_text = typer.style("Important Info", fg="blue", underline=True)
    typer.echo(f"Note: {styled_text}")

if __name__ == "__main__":
    typer.run(show_status)

Interactive Input

import typer

def interactive_setup():
    """Interactive application setup."""
    typer.echo("Welcome to App Setup!")
    
    name = typer.prompt("Your name")
    age = typer.prompt("Your age", type=int, default=25)
    email = typer.prompt("Email address")
    
    password = typer.prompt("Password", hide_input=True, confirmation_prompt=True)
    
    typer.echo(f"\\nHello {name}! You are {age} years old.")
    typer.echo(f"Email: {email}")
    
    if typer.confirm("Save configuration?"):
        typer.secho("Configuration saved!", fg="green")
    else:
        typer.secho("Configuration discarded.", fg="yellow")

if __name__ == "__main__":
    typer.run(interactive_setup)

Progress Bar

import typer
import time

def process_items():
    """Demonstrate progress bar usage."""
    items = list(range(50))
    
    with typer.progressbar(items, label="Processing items") as progress:
        for item in progress:
            # Simulate processing time
            time.sleep(0.1)
    
    typer.secho("All items processed!", fg="green")

if __name__ == "__main__":
    typer.run(process_items)

File Operations

import typer
from pathlib import Path

def safe_file_write(
    content: str,
    filename: str = typer.Option("output.txt", help="Output filename")
):
    """Safely write content to file."""
    try:
        with typer.open_file(filename, "w", atomic=True) as f:
            f.write(content)
        
        formatted_name = typer.format_filename(filename)
        typer.secho(f"✓ Wrote to {formatted_name}", fg="green")
        
    except Exception as e:
        typer.secho(f"✗ Error writing file: {e}", fg="red", err=True)
        raise typer.Exit(1)

if __name__ == "__main__":
    typer.run(safe_file_write)

Terminal Control

import typer
import time

def terminal_demo():
    """Demonstrate terminal control functions."""
    typer.echo("Terminal Demo Starting...")
    time.sleep(2)
    
    typer.clear()
    typer.echo("Screen cleared!")
    
    typer.echo("\\nPress any key to continue...")
    char = typer.getchar()
    typer.echo(f"You pressed: {char}")
    
    if typer.confirm("Show large text via pager?"):
        large_text = "\\n".join(f"Line {i}: Some content here" for i in range(100))
        typer.echo_via_pager(large_text)
    
    typer.pause("Press any key to exit...")

if __name__ == "__main__":
    typer.run(terminal_demo)

Text Editor Integration

import typer

def edit_config():
    """Edit configuration using external editor."""
    initial_config = """# Application Configuration
debug = false
host = localhost
port = 8000
"""
    
    typer.echo("Opening editor for configuration...")
    edited_config = typer.edit(initial_config, extension=".conf")
    
    if edited_config:
        typer.echo("Configuration updated:")
        typer.echo(edited_config)
        
        if typer.confirm("Save changes?"):
            with open("config.conf", "w") as f:
                f.write(edited_config)
            typer.secho("Configuration saved!", fg="green")
    else:
        typer.secho("No changes made.", fg="yellow")

if __name__ == "__main__":
    typer.run(edit_config)

Install with Tessl CLI

npx tessl i tessl/pypi-typer

docs

color-constants.md

core-application.md

file-handling.md

index.md

parameter-configuration.md

terminal-utilities.md

testing-support.md

tile.json