CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-xonsh

Python-powered shell providing superset of Python with shell primitives for cross-platform command execution and automation.

Overview
Eval results
Files

builtins-api.mddocs/

Built-ins API

Overview

Xonsh's built-ins provide the core functionality available in all xonsh sessions. The central component is the XSH singleton (XonshSession), which manages all session state including the executer, environment, shell, and history. Built-in functions provide utilities for path manipulation, subprocess execution, and interactive help.

XonshSession (XSH)

Core Session Object

from xonsh.built_ins import XSH, XonshSession

class XonshSession:
    """Central session object managing all xonsh components."""
    
    def __init__(self):
        """Initialize xonsh session.
        
        Attributes
        ----------
        execer : Execer
            Code execution engine
        ctx : dict
            Execution context/namespace
        builtins_loaded : bool
            Whether built-ins have been loaded
        history : History
            Command history manager
        shell : Shell
            Interactive shell instance
        env : Env
            Environment variable manager
        exit : int or None
            Exit code for session termination
        """
        self.execer = None
        self.ctx = {}
        self.builtins_loaded = False
        self.history = None
        self.shell = None
        self.env = None
        self.exit = None
        
# Global session singleton
XSH: XonshSession  # Main xonsh session instance

Session Access Patterns

from xonsh.built_ins import XSH

# Access core components
executer = XSH.execer        # Code execution
environment = XSH.env        # Environment variables  
shell = XSH.shell           # Interactive shell
history = XSH.history       # Command history
context = XSH.ctx           # Execution namespace

# Check session state
if XSH.builtins_loaded:
    print("Xonsh session fully initialized")
    
# Session termination
XSH.exit = 0  # Set exit code

Built-in Functions

Help and Inspection

from xonsh.built_ins import helper, superhelper

def helper(obj, name: str = "") -> object:
    """Show help for an object and return it.
    
    Parameters
    ----------
    obj : object
        Object to get help for
    name : str, optional
        Name to display for the object
        
    Returns
    -------
    object
        The original object (for chaining)
    """
    
def superhelper(obj, name: str = "") -> object:
    """Show detailed help for an object and return it.
    
    Parameters
    ----------
    obj : object
        Object to get detailed help for
    name : str, optional 
        Name to display for the object
        
    Returns
    -------
    object
        The original object (for chaining)
    """

# Usage examples
help_result = helper(list)           # Show help for list type
detailed_help = superhelper(dict)    # Show detailed help for dict
chained = helper(str.split, "split") # Show help with custom name

Path and File Operations

from xonsh.built_ins import globpath, expand_path, pathsearch

def globpath(pattern: str, ignore_hidden: bool = False, 
             return_empty: bool = False) -> list[str]:
    """Glob file paths matching a pattern.
    
    Parameters
    ----------
    pattern : str
        Glob pattern (supports *, ?, [], etc.)
    ignore_hidden : bool, default False
        Whether to ignore hidden files
    return_empty : bool, default False
        Whether to return empty list if no matches
        
    Returns
    -------
    list[str]
        List of matching file paths
    """

def expand_path(path: str) -> str:
    """Expand user home directory and environment variables.
    
    Parameters
    ----------
    path : str
        Path potentially containing ~ or $VAR
        
    Returns
    -------
    str
        Expanded absolute path
    """
    
def pathsearch(func, path: str, pymode: bool = False, 
               ignore_hidden: bool = False) -> list[str]:
    """Search for files matching a function criteria.
    
    Parameters
    ----------
    func : callable
        Function to test each path
    path : str
        Directory path to search
    pymode : bool, default False
        Whether to use Python mode evaluation
    ignore_hidden : bool, default False
        Whether to ignore hidden files
        
    Returns
    -------
    list[str]
        List of matching paths
    """

# Usage examples
py_files = globpath("*.py")                    # Find Python files
config_files = globpath("~/.config/*")         # Expand home directory
home_path = expand_path("~/Documents")         # Expand to absolute path
executables = pathsearch(lambda p: os.access(p, os.X_OK), "/usr/bin")

Regular Expression Search

from xonsh.built_ins import regexsearch, globsearch, reglob

def regexsearch(func, pattern: str, path: str = ".") -> list[str]:
    """Search files using regex pattern.
    
    Parameters
    ----------
    func : callable
        Function to apply to matching content
    pattern : str
        Regular expression pattern
    path : str, default "."
        Directory to search
        
    Returns
    -------
    list[str]
        List of matching results
    """
    
def globsearch(func, pattern: str) -> list[str]:
    """Search using glob pattern and apply function.
    
    Parameters
    ----------
    func : callable
        Function to apply to each match
    pattern : str
        Glob pattern for file matching
        
    Returns
    -------
    list[str]
        List of function results
    """

def reglob(path: str, parts: list = None, i: int = None) -> list[str]:
    """Regular expression-based globbing.
    
    Parameters
    ----------
    path : str
        Path pattern with regex components
    parts : list, optional
        Path components for recursive processing
    i : int, optional
        Current part index
        
    Returns
    -------
    list[str]
        List of matching paths
    """

# Usage examples
log_files = globsearch(str, "*.log")           # Find log files
py_imports = regexsearch(str, r"^import\s+", ".")  # Find import statements
regex_paths = reglob(r"test_.*\.py")           # Regex-based file matching

Subprocess Execution

Subprocess Capture Functions

from xonsh.built_ins import (subproc_captured_stdout, subproc_captured_inject,
                             subproc_captured_object, subproc_captured_hiddenobject,
                             subproc_uncaptured)

def subproc_captured_stdout(cmd: list[str]) -> str:
    """Execute subprocess and capture stdout as string.
    
    Parameters
    ----------
    cmd : list[str]
        Command and arguments to execute
        
    Returns
    -------
    str
        Captured stdout content
    """

def subproc_captured_object(cmd: list[str]) -> object:
    """Execute subprocess and return process object.
    
    Parameters
    ----------
    cmd : list[str]
        Command and arguments to execute
        
    Returns
    -------
    object
        Process object with stdout, stderr, returncode
    """
    
def subproc_captured_hiddenobject(cmd: list[str]) -> object:
    """Execute subprocess with hidden output, return process object.
    
    Parameters
    ----------
    cmd : list[str]
        Command and arguments to execute
        
    Returns
    -------
    object
        Process object (output not displayed)
    """

def subproc_uncaptured(cmd: list[str]) -> None:
    """Execute subprocess without capturing output.
    
    Parameters
    ----------
    cmd : list[str]
        Command and arguments to execute
    """

def subproc_captured_inject(cmd: list[str]) -> str:
    """Execute subprocess and inject output into current context.
    
    Parameters
    ----------
    cmd : list[str]
        Command and arguments to execute
        
    Returns
    -------
    str
        Captured output (also injected to context)
    """

# Usage examples
output = subproc_captured_stdout(['ls', '-la'])        # Get stdout
proc = subproc_captured_object(['git', 'status'])      # Get process object
hidden_proc = subproc_captured_hiddenobject(['make'])  # Hidden execution
subproc_uncaptured(['vim', 'file.txt'])               # Interactive command

Macro System

Macro Execution

from xonsh.built_ins import call_macro, enter_macro

def call_macro(name: str, *args, **kwargs) -> object:
    """Call a xonsh macro by name.
    
    Parameters
    ----------
    name : str
        Macro name to call
    *args
        Positional arguments to macro
    **kwargs
        Keyword arguments to macro
        
    Returns
    -------
    object
        Macro return value
    """

def enter_macro(name: str, *args, **kwargs) -> object:
    """Enter a macro context.
    
    Parameters
    ----------
    name : str
        Macro name to enter
    *args
        Positional arguments
    **kwargs
        Keyword arguments
        
    Returns
    -------
    object
        Macro context result
    """

# Macro usage examples
result = call_macro('my_macro', arg1='value')
with enter_macro('context_macro'):
    # Code executed in macro context
    pass

Data Type Utilities

String and List Processing

from xonsh.built_ins import (list_of_strs_or_callables, 
                             list_of_list_of_strs_outer_product,
                             path_literal)

def list_of_strs_or_callables(items) -> list:
    """Convert input to list of strings or callables.
    
    Parameters
    ----------
    items : various
        Input to convert to list
        
    Returns
    -------
    list
        List of strings or callable objects
    """

def list_of_list_of_strs_outer_product(items) -> list[list[str]]:
    """Create outer product of string lists.
    
    Parameters
    ----------
    items : list[list[str]]
        List of string lists to combine
        
    Returns
    -------
    list[list[str]]
        Outer product combinations
    """
    
def path_literal(path: str) -> str:
    """Convert path to literal path string.
    
    Parameters
    ----------
    path : str
        Path to convert
        
    Returns
    -------
    str
        Literal path string
    """

# Usage examples
str_list = list_of_strs_or_callables(['a', 'b', lambda: 'c'])
combinations = list_of_list_of_strs_outer_product([['a', 'b'], ['1', '2']])
literal_path = path_literal('/path/with spaces')

F-string Field Evaluation

from xonsh.built_ins import eval_fstring_field

def eval_fstring_field(field: str, ctx: dict) -> str:
    """Evaluate f-string field in given context.
    
    Parameters
    ----------
    field : str
        F-string field expression
    ctx : dict
        Evaluation context
        
    Returns
    -------
    str
        Evaluated field value
    """

# Usage example
context = {'name': 'world', 'x': 42}
result = eval_fstring_field('name.upper()', context)  # 'WORLD'
result = eval_fstring_field('x * 2', context)         # '84'

Session Management

Session Attributes

from xonsh.built_ins import XSH

# Core session components access
executer = XSH.execer           # Execer instance
environment = XSH.env           # Environment manager
shell_instance = XSH.shell      # Shell interface
command_history = XSH.history   # History manager

# Session state
context = XSH.ctx               # Execution namespace
exit_code = XSH.exit            # Session exit code
loaded = XSH.builtins_loaded    # Initialization status

# Caching systems
commands_cache = XSH.commands_cache  # Command lookup cache
modules_cache = XSH.modules_cache    # Python module cache

# Job management
job_manager = XSH.all_jobs      # Active job manager

# Stream handling  
stdout_uncaptured = XSH.stdout_uncaptured  # Uncaptured stdout
stderr_uncaptured = XSH.stderr_uncaptured  # Uncaptured stderr

Session Lifecycle

from xonsh.built_ins import XSH

# Session initialization check
if not XSH.builtins_loaded:
    print("Session not fully initialized")

# Graceful session termination
def exit_xonsh(code=0):
    """Exit xonsh session with code."""
    XSH.exit = code
    
# Session cleanup
def cleanup_session():
    """Clean up session resources."""
    if XSH.shell:
        XSH.shell.reset()
    if XSH.history:
        XSH.history.flush()

The built-ins API provides the foundation for all xonsh functionality, offering both low-level session management and high-level utility functions for common shell and scripting tasks.

Install with Tessl CLI

npx tessl i tessl/pypi-xonsh

docs

aliases.md

api-package.md

builtins-api.md

completion.md

configuration.md

directory-management.md

events.md

index.md

scripting.md

shell-interface.md

tile.json