{"id":5088,"library":"types-pexpect","title":"Typing Stubs for pexpect","description":"types-pexpect provides static type annotations (stub files) for the pexpect library, enabling type checkers like MyPy and Pyright to perform static analysis, type inference, and autocompletion for code using pexpect. It is part of the typeshed project and is automatically released from typeshed's internal machinery, often with daily updates, to provide accurate annotations for the corresponding pexpect runtime versions (currently targeting pexpect==4.9.*).","status":"active","version":"4.9.0.20260408","language":"en","source_language":"en","source_url":"https://github.com/python/typeshed","tags":["typing","stubs","pexpect","typeshed","type checking","automation","interactive processes"],"install":[{"cmd":"pip install pexpect types-pexpect","lang":"bash","label":"Install pexpect and its typing stubs"}],"dependencies":[{"reason":"This package provides type stubs for the 'pexpect' runtime library, which must be installed separately.","package":"pexpect","optional":false},{"reason":"Requires Python 3.10 or newer.","package":"python","optional":false}],"imports":[{"note":"types-pexpect is a stub-only package. You import symbols directly from the 'pexpect' library, and type checkers will automatically use the installed stubs for static analysis.","symbol":"spawn","correct":"import pexpect\nchild = pexpect.spawn('command')"},{"note":"types-pexpect does not contain runtime code; it only provides type information for existing pexpect symbols.","symbol":"EOF","correct":"import pexpect\nchild.expect(pexpect.EOF)"}],"quickstart":{"code":"import pexpect\nimport os\n\ndef run_and_check_type() -> str:\n    # Simulate a command that prints to stdout\n    script_path = 'temp_script.py'\n    with open(script_path, 'w') as f:\n        f.write(\"import sys; sys.stdout.write('hello world\\n')\")\n    \n    try:\n        child = pexpect.spawn(f'python {script_path}')\n        child.expect('hello world\\r\\n') # pexpect typically sees \\r\\n\n        # In pexpect 4.9, 'before' is AnyStr | None\n        # You need to explicitly decode if you expect a str and were expecting bytes\n        # The types-pexpect 4.9.0 stubs reflect this (Issue #11382 on typeshed).\n        output_bytes = child.before\n        if output_bytes is None:\n            return ''\n        return output_bytes.decode('utf-8')\n\n    except pexpect.exceptions.TIMEOUT:\n        print('TIMEOUT exception')\n        return ''\n    except pexpect.exceptions.EOF:\n        print('EOF exception')\n        return ''\n    finally:\n        if os.path.exists(script_path):\n            os.remove(script_path)\n\nif __name__ == '__main__':\n    result = run_and_check_type()\n    print(f\"Captured output: {result}\")\n\n    # To run type checking, save this as `your_script.py`\n    # Then run: `mypy your_script.py` after installing `mypy`\n    # Expected output: No issues found\n","lang":"python","description":"This quickstart demonstrates a basic usage of pexpect with type checking. First, ensure both `pexpect` and `types-pexpect` are installed. The example spawns a simple Python script, captures its output, and decodes it. A type checker like MyPy can then verify the type correctness, leveraging the `types-pexpect` stubs. For instance, the `child.before` attribute's type (AnyStr | None) is correctly recognized."},"warnings":[{"fix":"Explicitly check if `child.before` is `None` before attempting to decode it, and handle the possibility of it being `bytes` by calling `.decode()`.","message":"Type changes in pexpect.spawn().before from 'str' to 'AnyStr | None' in types-pexpect 4.9.0 stubs. If your code previously assumed `pexpect.spawn().before` would always be `str` and directly called `.decode()` without checking for `None` or handling `bytes`, type checkers will now flag this as an error.","severity":"breaking","affected_versions":"types-pexpect >=4.9.0.20240208 (corresponding to pexpect 4.9.*)"},{"fix":"Always ensure both `pexpect` and `types-pexpect` are installed via `pip install pexpect types-pexpect`.","message":"Installing `types-pexpect` does not install the `pexpect` runtime library itself. You must install `pexpect` separately for your code to run, as `types-pexpect` only provides type information.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Explicitly expect `\\r\\n` for line endings. For general stream matching, avoid `$` for end-of-line and understand that regular expressions operate on the incrementally read buffer.","message":"Regular expression matching for end-of-line (`$` or `\\n`) in `expect()` can be tricky due to how pseudo-TTYs handle line endings (typically `\\r\\n`). `$` often matches the end of the *current buffer*, not a logical line end, because Pexpect reads character by character.","severity":"gotcha","affected_versions":"All versions of pexpect (reflected in stubs)"},{"fix":"Pexpect 4.0+ mitigates this with a default delay. If issues persist, consider adding a small `time.sleep()` before `sendline()`, or adjust the `delaybeforesend` attribute of the `spawn` object.","message":"A common 'timing issue with send() and sendline()' exists when interacting with applications that prompt for passwords. If `sendline()` is called immediately after `expect()` for a password prompt, the password might be echoed before the child application turns off echo.","severity":"gotcha","affected_versions":"All versions of pexpect (pexpect 4.0+ adds a default delay, but custom applications might still trigger it)"}],"env_vars":null,"last_verified":"2026-04-12T00:00:00.000Z","next_check":"2026-07-11T00:00:00.000Z"}