Typing Stubs for pexpect
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
- breaking 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.
- gotcha 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.
- gotcha 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.
- gotcha 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.
Install
-
pip install pexpect types-pexpect
Imports
- spawn
import pexpect child = pexpect.spawn('command') - EOF
import pexpect child.expect(pexpect.EOF)
Quickstart
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