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

xonsh

Overview

Xonsh (pronounced "conch") is a Python-powered shell that combines the best of shell functionality with Python scripting capabilities. It provides a superset of Python syntax with shell primitives, enabling seamless integration between Python code and shell commands in a single interactive session. Xonsh supports cross-platform command execution, extensive customization through xontribs (extensions), sophisticated tab completion, and rich environment management.

Package Information

  • Name: xonsh
  • Type: Shell/Interactive Environment
  • Language: Python
  • Version: 0.19.9
  • License: BSD 2-Clause License
  • Installation: pip install xonsh

Dependencies

  • Python: >=3.9
  • Optional: prompt-toolkit (for enhanced shell interface)

Core Imports

# Basic xonsh imports
from xonsh.built_ins import XSH  # Main xonsh singleton
from xonsh.shell import Shell    # Shell interface
from xonsh.execer import Execer  # Code execution engine

# Environment and configuration
from xonsh.environ import Env    # Environment management
from xonsh.built_ins import XSH     # Access to aliases via XSH.aliases

# API modules for pure Python usage  
from xonsh.api import subprocess  # Subprocess wrappers
from xonsh.api import os         # OS utilities

# Completion system
from xonsh.completer import Completer
from xonsh.completers.tools import RichCompletion, Completion

# Xontribs (extensions)
from xonsh.xontribs import xontribs_load, get_xontribs

Basic Usage

Starting Xonsh Shell

# Start xonsh shell programmatically
from xonsh.main import main
main()

# Or execute xonsh code
from xonsh.built_ins import XSH
XSH.execer.eval('ls -la')

Environment Access

from xonsh.built_ins import XSH

# Access environment variables
env = XSH.env
print(env['PATH'])
env['MY_VAR'] = 'value'

# Environment swapping
with env.swap(DEBUG=True):
    # Temporary environment changes
    pass

Subprocess Execution

from xonsh.api.subprocess import run, check_output

# Run commands with xonsh syntax
result = run(['ls', '-la'])
output = check_output(['echo', 'hello world'])

# Captured subprocess execution
from xonsh.built_ins import subproc_captured_stdout
stdout = subproc_captured_stdout(['ls', '-la'])

Architecture

Xonsh is built around several key components:

Core Components

  • XonshSession (XSH): Central singleton managing all xonsh state
  • Execer: Parses and executes xonsh code (Python + shell syntax)
  • Shell: Interactive shell interface with various backends
  • Environment (Env): Enhanced environment variable management
  • Completer: Tab completion system with pluggable completers

Key Subsystems

  • Parsers: Handle xonsh syntax parsing and AST transformation
  • Procs: Process and pipeline management
  • History: Command history storage and retrieval
  • Aliases: Command aliasing system
  • Xontribs: Extension/plugin system
  • Completers: Modular completion providers

Capabilities

Shell Interface

Core shell functionality including command execution, pipeline management, and interactive features.

from xonsh.shell import Shell

# Create shell instance
shell = Shell()
shell.cmdloop()  # Start interactive loop

# Execute single command
shell.default("ls -la")

Built-ins API

Built-in functions, the XSH singleton, and core xonsh utilities.

from xonsh.built_ins import XSH, helper, globpath

# Access main xonsh session
session = XSH
execer = XSH.execer
env = XSH.env
history = XSH.history

# Built-in functions
help_info = helper(list)  # Get help for objects
files = globpath("*.py")  # Glob file patterns

Scripting

Python integration, code execution, and subprocess handling.

from xonsh.execer import Execer

# Execute xonsh code
execer = Execer()
result = execer.eval("ls | wc -l", ctx={})
execer.exec("print('Hello from xonsh')", ctx={})

Completion

Tab completion system with extensible completers.

from xonsh.completer import Completer
from xonsh.completers.tools import RichCompletion

# Create completer
completer = Completer()
completions = completer.complete("gi", "git status", 0, 2)

# Rich completions
rich_comp = RichCompletion("status", description="Show working tree status")

Configuration

Environment variables, aliases, and xontrib management.

from xonsh.environ import Env
from xonsh.aliases import FuncAlias
from xonsh.xontribs import xontribs_load

# Environment configuration
env = Env()
env['XONSH_SHOW_TRACEBACK'] = True

# Create function alias  
def my_func():
    return "Hello world"
alias = FuncAlias("hello", my_func)

# Load xontrib
xontribs_load(['vox'])  # Virtual environment management

Directory Management

Directory navigation, stack operations, and path utilities.

from xonsh.dirstack import cd, pushd_fn, popd_fn, dirs_fn, with_pushd

# Directory navigation
cd(['/tmp'])          # Change directory
pushd_fn(['/var'])    # Push directory to stack
popd_fn([])           # Pop from stack

# Context manager for temporary directory changes
with with_pushd('/tmp'):
    # Work in /tmp
    pass

Aliases

Command aliases, function shortcuts, and command transformations.

from xonsh.aliases import Aliases, FuncAlias, ExecAlias
from xonsh.built_ins import XSH

# Access global aliases
aliases = XSH.aliases

# Function alias
def greet(args, stdin=None):
    name = args[0] if args else "World"
    print(f"Hello, {name}!")

aliases['greet'] = FuncAlias(greet)

# Executable alias
aliases['ll'] = ExecAlias('ls -la')

Events

Event system for shell lifecycle hooks and customization.

from xonsh.events import events

# Register event handlers
@events.on_precommand
def before_command(cmd: str):
    """Called before command execution."""
    print(f"About to run: {cmd}")

@events.on_postcommand
def after_command(cmd: str, rtn: int, out: str, ts: list):
    """Called after command execution."""
    if rtn != 0:
        print(f"Command failed with code {rtn}")

API Package

Pure Python API for external tools and libraries.

from xonsh.api.subprocess import run, check_call, check_output
from xonsh.api.os import rmtree, indir

# Enhanced subprocess operations
result = run(['ls', '-la'], cwd='/tmp')
output = check_output(['git', 'rev-parse', 'HEAD'])

# Cross-platform OS utilities
with indir('/tmp'):
    # Work in temporary directory
    rmtree('old_directory', force=True)

Event System

Xonsh provides an extensive event system for customization:

from xonsh.events import events

# Register event handlers
@events.on_precommand
def before_command(cmd):
    print(f"About to run: {cmd}")

@events.on_postcommand  
def after_command(cmd, rtn, out, ts):
    print(f"Command '{cmd}' returned {rtn}")

Advanced Features

Custom Completers

from xonsh.completers.tools import contextual_completer

@contextual_completer
def my_completer(context):
    """Custom completer function"""
    if context.command and context.command.arg_index == 1:
        return ['option1', 'option2', 'option3']
    return set()

Process Management

from xonsh.procs.jobs import jobs, fg, bg
from xonsh.procs.pipelines import Pipeline

# Job control
job_list = jobs()  # List active jobs
fg(1)             # Foreground job 1
bg(1)             # Background job 1

# Pipeline creation
pipeline = Pipeline(['ls', '-la'], ['grep', 'py'])

This documentation provides comprehensive coverage of xonsh's capabilities, enabling AI agents to effectively use xonsh for shell automation, Python scripting integration, and interactive computing tasks.

Install with Tessl CLI

npx tessl i tessl/pypi-xonsh
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/xonsh@0.19.x