Typing Stubs for pexpect

4.9.0.20260408 · active · verified Sun Apr 12

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.*).

Warnings

Install

Imports

Quickstart

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.

import pexpect
import os

def run_and_check_type() -> str:
    # Simulate a command that prints to stdout
    script_path = 'temp_script.py'
    with open(script_path, 'w') as f:
        f.write("import sys; sys.stdout.write('hello world\n')")
    
    try:
        child = pexpect.spawn(f'python {script_path}')
        child.expect('hello world\r\n') # pexpect typically sees \r\n
        # In pexpect 4.9, 'before' is AnyStr | None
        # You need to explicitly decode if you expect a str and were expecting bytes
        # The types-pexpect 4.9.0 stubs reflect this (Issue #11382 on typeshed).
        output_bytes = child.before
        if output_bytes is None:
            return ''
        return output_bytes.decode('utf-8')

    except pexpect.exceptions.TIMEOUT:
        print('TIMEOUT exception')
        return ''
    except pexpect.exceptions.EOF:
        print('EOF exception')
        return ''
    finally:
        if os.path.exists(script_path):
            os.remove(script_path)

if __name__ == '__main__':
    result = run_and_check_type()
    print(f"Captured output: {result}")

    # To run type checking, save this as `your_script.py`
    # Then run: `mypy your_script.py` after installing `mypy`
    # Expected output: No issues found

view raw JSON →