Pure Python module for spawning child applications and controlling them automatically with expect-like functionality.
npx @tessl/cli install tessl/pypi-pexpect@4.9.0A 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.
pip install pexpectimport pexpectCommon 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 REPLWrapperimport 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')Pexpect is built around several core concepts:
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.
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): ...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): ...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): ...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'): ...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): ...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): ...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 informationclass 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 ExceptionPxsshCommon 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}')