Pexpect

4.9.0 · active · verified Fri Mar 27

Pure Python module for spawning child applications and controlling them — automates interactive CLI programs like ssh, ftp, passwd. Current version is 4.9.0 (Nov 2023). pexpect.spawn requires Unix/Linux (uses the pty module) — not available on Windows. For Windows use pexpect.PopenSpawn instead. Low maintenance activity since 2023.

Warnings

Install

Imports

Quickstart

Always pass encoding='utf-8'. expect() returns index. Use PopenSpawn on Windows.

import pexpect

# Basic spawn with string encoding (recommended)
child = pexpect.spawn(
    'python3 -c "name = input(\"Name: \"); print(f\"Hello {name}!\")"',
    encoding='utf-8',
    timeout=10
)

# expect() waits for a pattern, returns the index of the match
child.expect('Name: ')
child.sendline('Alice')
child.expect(pexpect.EOF)   # wait for program to finish
print(child.before)          # 'Hello Alice!\r\n'

# Multi-pattern expect
index = child.expect(['pattern1', 'pattern2', pexpect.EOF, pexpect.TIMEOUT])
# index 0 = matched 'pattern1'
# index 1 = matched 'pattern2'
# index 2 = EOF (process ended)
# index 3 = timeout

# Windows: use PopenSpawn (no pty, no interactive echo)
from pexpect import popen_spawn
child = popen_spawn.PopenSpawn('python --version', encoding='utf-8')
child.expect(pexpect.EOF)
print(child.before)

view raw JSON →