{"id":237,"library":"pexpect","title":"Pexpect","description":"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.","status":"active","version":"4.9.0","language":"python","source_language":"en","source_url":"https://pexpect.readthedocs.io/en/stable/","tags":["cli-automation","interactive","ssh","terminal","subprocess","expect","testing"],"install":[{"cmd":"pip install pexpect","lang":"bash","label":"Standard"}],"dependencies":[{"reason":"Required on Unix for pty-based spawn. Installed automatically.","package":"ptyprocess>=0.5","optional":false}],"imports":[{"wrong":"import pexpect","symbol":"spawn","correct":"from pexpect import spawn"},{"symbol":"EOF","correct":"from pexpect import EOF"},{"symbol":"TIMEOUT","correct":"from pexpect import TIMEOUT"}],"quickstart":{"code":"import pexpect\n\n# Basic spawn with string encoding (recommended)\nchild = pexpect.spawn(\n    'python3 -c \"name = input(\\\"Name: \\\"); print(f\\\"Hello {name}!\\\")\"',\n    encoding='utf-8',\n    timeout=10\n)\n\n# expect() waits for a pattern, returns the index of the match\nchild.expect('Name: ')\nchild.sendline('Alice')\nchild.expect(pexpect.EOF)   # wait for program to finish\nprint(child.before)          # 'Hello Alice!\\r\\n'\n\n# Multi-pattern expect\nindex = child.expect(['pattern1', 'pattern2', pexpect.EOF, pexpect.TIMEOUT])\n# index 0 = matched 'pattern1'\n# index 1 = matched 'pattern2'\n# index 2 = EOF (process ended)\n# index 3 = timeout\n\n# Windows: use PopenSpawn (no pty, no interactive echo)\nfrom pexpect import popen_spawn\nchild = popen_spawn.PopenSpawn('python --version', encoding='utf-8')\nchild.expect(pexpect.EOF)\nprint(child.before)","lang":"python","description":"Always pass encoding='utf-8'. expect() returns index. Use PopenSpawn on Windows."},"warnings":[{"fix":"On Windows use pexpect.popen_spawn.PopenSpawn instead. PopenSpawn lacks interactive TTY features but works cross-platform.","message":"pexpect.spawn is not available on Windows — it requires the pty module which only exists on Unix. Importing pexpect works, but calling pexpect.spawn() raises ImportError or OSError on Windows.","severity":"breaking","affected_versions":"all"},{"fix":"Replace child.expect('pattern', async=True) with child.expect('pattern', async_=True)","message":"The async= parameter was renamed to async_= as async became a Python keyword in 3.7. Using async= raises SyntaxError on Python 3.7+.","severity":"breaking","affected_versions":">= 4.3"},{"fix":"Always pass encoding='utf-8': pexpect.spawn('cmd', encoding='utf-8'). Then expect() patterns and before/after are strings.","message":"Without encoding='utf-8', child.before and child.after return bytes, not str. Most tutorials show str patterns but they fail with bytes. Always specify encoding at spawn time.","severity":"gotcha","affected_versions":"all"},{"fix":"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()","message":"pexpect.TIMEOUT and pexpect.EOF are classes, not exceptions. They are passed to expect() as patterns (expect([pexpect.EOF, pexpect.TIMEOUT])), not caught with except. Catching them with except does not work as expected.","severity":"gotcha","affected_versions":"all"},{"fix":"To get all output: child.expect(pexpect.EOF); print(child.before) captures everything before EOF.","message":"child.before contains output BEFORE the matched pattern. child.after contains the matched pattern itself. Output AFTER the match is buffered internally. Accessing child.before after EOF gives all remaining output.","severity":"gotcha","affected_versions":"all"},{"fix":"Use the pyte package for terminal emulation instead.","message":"pexpect.screen and pexpect.ANSI modules are deprecated. Do not import from them.","severity":"gotcha","affected_versions":"all"},{"fix":"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.","message":"The child process terminated prematurely, likely due to an internal error (e.g., SyntaxError, unhandled exception, command not found, permissions error) or reaching its natural end of output, before the expected pattern could be found. Pexpect reports this as `pexpect.exceptions.EOF`.","severity":"gotcha","affected_versions":"all"},{"fix":"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.","message":"pexpect.exceptions.EOF can be raised if the child process terminates unexpectedly before the expected pattern is found. This often indicates an error or crash within the child process itself (e.g., SyntaxError, unhandled exception, program exit).","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"search_vec":"'2023':25,46 '4.9.0':23 'activ':44 'applic':8 'autom':12,49 'avail':34 'child':7 'cli':14,48 'cli-autom':47 'control':10 'current':20 'expect':54 'ftp':18 'instead':41 'interact':13,50 'like':16 'low':42 'mainten':43 'modul':4,32 'nov':24 'passwd':19 'pexpect':1 'pexpect.popenspawn':40 'pexpect.spawn':26 'program':15 'pti':31 'pure':2 'python':3 'requir':27 'sinc':45 'spawn':6 'ssh':17,51 'subprocess':53 'termin':52 'test':55 'unix/linux':28 'use':29,39 'version':21 'window':36,38","created_at":"2026-03-27T05:08:38.185969+00:00","updated_at":"2026-04-16T17:59:07.471668+00:00","problems":null,"ecosystem":"pypi","meta_description":null,"install_score":100,"quickstart_score":0,"quickstart_tag":"stale","pypi_latest":"4.9.0","cli_name":"","cli_version":null,"type":"library","homepage":"https://pexpect.readthedocs.io/","github":"https://github.com/pexpect/pexpect","docs":"https://pexpect.readthedocs.io/","changelog":"https://pexpect.readthedocs.io/en/stable/history.html","pypi":"https://pypi.org/project/pexpect/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["testing","devops"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-07-03","last_verified":"2026-07-03","next_check":"2026-08-02","install_tag":"verified"}}