or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

alternative-spawning.mdindex.mdpattern-matching.mdprocess-control.mdrepl-automation.mdssh-operations.mdutilities.md
tile.json

tessl/pypi-pexpect

Pure Python module for spawning child applications and controlling them automatically with expect-like functionality.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pexpect@4.9.x

To install, run

npx @tessl/cli install tessl/pypi-pexpect@4.9.0

index.mddocs/

Pexpect

A pure Python module for spawning child applications and controlling them automatically. Pexpect provides expect-like functionality for automating interactive applications such as ssh, ftp, passwd, telnet, and more. It enables programmatic control of interactive console applications as if a human were typing commands.

Package Information

  • Package Name: pexpect
  • Language: Python
  • Installation: pip install pexpect
  • Requirements: Python 2.7 or 3.x, ptyprocess>=0.5

Core Imports

import pexpect

Common imports for specific functionality:

from pexpect import spawn, run, EOF, TIMEOUT, ExceptionPexpect
from pexpect.pxssh import pxssh
from pexpect.popen_spawn import PopenSpawn
from pexpect.fdpexpect import fdspawn
from pexpect.socket_pexpect import SocketSpawn
from pexpect.replwrap import REPLWrapper

Basic Usage

import pexpect

# Simple command execution with run()
output = pexpect.run('ls -la')
print(output.decode())

# Interactive process control with spawn
child = pexpect.spawn('ssh user@hostname')
child.expect('Password:')
child.sendline('mypassword')
child.expect('$ ')
child.sendline('ls')
child.expect('$ ')
print(child.before.decode())
child.close()

# Context manager support
with pexpect.spawn('ftp example.com') as child:
    child.expect('Name:')
    child.sendline('anonymous')
    child.expect('ftp>')
    child.sendline('quit')

Architecture

Pexpect is built around several core concepts:

  • spawn: Main class for creating and controlling child processes using pseudo-terminals (PTY)
  • SpawnBase: Abstract base class providing common functionality for all spawn implementations
  • Expecter: Pattern matching engine that searches for text patterns in child output
  • Searchers: String and regex pattern matching classes for the expect system
  • Alternative Spawn Classes: PopenSpawn (subprocess-based), fdspawn (file descriptor), SocketSpawn (sockets), pxssh (SSH)

The library provides both high-level functions for simple tasks (run()) and powerful classes for complex interactive automation scenarios.

Note: The screen and ANSI modules are deprecated. For terminal screen emulation, the maintainers recommend using the pyte library instead.

Capabilities

Process Spawning and Control

Core functionality for spawning and controlling child processes using pseudo-terminals. Includes the main spawn class and high-level run function for command execution.

class spawn:
    def __init__(self, command, args=[], timeout=30, maxread=2000, 
                 searchwindowsize=None, logfile=None, cwd=None, env=None,
                 ignore_sighup=False, echo=True, preexec_fn=None,
                 encoding=None, codec_errors='strict', dimensions=None,
                 use_poll=False): ...

def run(command, timeout=30, withexitstatus=False, events=None,
        extra_args=None, logfile=None, cwd=None, env=None, **kwargs): ...

Process Control

Pattern Matching and Expect Operations

Powerful pattern matching system for waiting for expected output from child processes. Supports both string and regular expression patterns with timeout handling.

def expect(self, pattern, timeout=-1, searchwindowsize=-1): ...
def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1): ...
def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1): ...

class searcher_string:
    def __init__(self, string, index): ...

class searcher_re:
    def __init__(self, pattern, index): ...

Pattern Matching

SSH Automation

Specialized SSH connection wrapper that extends spawn with SSH-specific functionality including automatic login, logout, and shell prompt handling.

class pxssh(spawn):
    def login(self, server, username, password=None, terminal_type='ansi',
              original_prompt=r"[#$]", login_timeout=10, port=None,
              auto_prompt_reset=True, ssh_key=None, quiet=True,
              sync_multiplier=1, check_local_ip=True, password_regex=None,
              ssh_tunnels=None, spawn_local_ssh=True, sync_original_prompt=True,
              ssh_config=None, cmd="ssh"): ...
    
    def logout(self): ...
    def prompt(self, timeout=-1): ...

SSH Operations

Alternative Process Control

Alternative spawn implementations for different communication mechanisms including subprocess-based spawning, file descriptor control, and socket communication.

class PopenSpawn(SpawnBase):
    def __init__(self, cmd, timeout=30, maxread=2000, searchwindowsize=None,
                 logfile=None, cwd=None, env=None, encoding=None,
                 codec_errors='strict', preexec_fn=None): ...

class fdspawn(SpawnBase):
    def __init__(self, fd, args=None, timeout=30, maxread=2000,
                 searchwindowsize=None, logfile=None, encoding=None,
                 codec_errors='strict'): ...

class SocketSpawn(SpawnBase):
    def __init__(self, socket, args=None, timeout=30, maxread=2000,
                 searchwindowsize=None, logfile=None, encoding=None,
                 codec_errors='strict'): ...

Alternative Spawning

REPL and Shell Automation

Tools for automating read-eval-print loops and interactive shells with customizable prompts and command execution.

class REPLWrapper:
    def __init__(self, cmd_or_spawn, orig_prompt, prompt_change=None,
                 new_prompt=None, extra_init_cmd=""): ...
    
    def run_command(self, command, timeout=-1, async_=False): ...

REPL Automation

Utilities and Helpers

Utility functions for common tasks including executable finding, command line parsing, and file system operations.

def which(filename, env=None): ...
def split_command_line(command_line): ...
def is_executable_file(path): ...

Utilities

Module Constants

Important constants available in the pexpect module:

# Special pattern types for expect operations
EOF: Exception  # Matches end-of-file condition
TIMEOUT: Exception  # Matches timeout condition

# Version information
__version__: str  # Current version string
__revision__: str  # Revision information

Exception Handling

class ExceptionPexpect(Exception):
    def __init__(self, value): ...
    def get_trace(self): ...

class EOF(ExceptionPexpect):
    """Raised when EOF is read from a child. Usually means the child has exited."""

class TIMEOUT(ExceptionPexpect):
    """Raised when a read time exceeds the timeout."""

class ExceptionPxssh(ExceptionPexpect):
    """Raised for pxssh exceptions."""

# Additional pxssh-specific exceptions available in pexpect.pxssh module
# from pexpect.pxssh import ExceptionPxssh

Common exception handling patterns:

import pexpect

try:
    child = pexpect.spawn('some_command')
    child.expect('expected_pattern', timeout=10)
except pexpect.TIMEOUT:
    print('Timeout waiting for pattern')
except pexpect.EOF:
    print('Child process ended unexpectedly')
except pexpect.ExceptionPexpect as e:
    print(f'Pexpect error: {e}')