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.
pip install pexpectVerified import paths — ran on the pinned version, not inferred.
Always pass encoding='utf-8'. expect() returns index. Use PopenSpawn on Windows.
On Windows use pexpect.popen_spawn.PopenSpawn instead. PopenSpawn lacks interactive TTY features but works cross-platform.
Replace child.expect('pattern', async=True) with child.expect('pattern', async_=True)Always pass encoding='utf-8': pexpect.spawn('cmd', encoding='utf-8'). Then expect() patterns and before/after are strings.Pass them as patterns in the expect list and check the returned index: index = child.expect(['pattern', pexpect.EOF, pexpect.TIMEOUT]); if index == 2: handle_timeout()
To get all output: child.expect(pexpect.EOF); print(child.before) captures everything before EOF.
Use the pyte package for terminal emulation instead.
Inspect the contents of `child.before` for error messages or diagnostic output from the child process. Fix the underlying issue in the child's command or script. To handle expected terminations gracefully without raising an exception, add `pexpect.EOF` to your expect list (e.g., `child.expect(['your pattern', pexpect.EOF])`) and check the returned index.
Examine the `child.before` buffer for error messages or tracebacks from the child process that explain its termination. Ensure the command or script executed by the child process is syntactically correct and robust, handling its own internal errors gracefully to prevent premature exit.