Last modified: Jun 01, 2025 By Alexander Williams

Install Pexpect in Python for Automation

Pexpect is a Python module for automating interactive applications. It works like the Unix expect tool. You can control and automate command-line programs with it.

This guide will show you how to install Pexpect in Python. You will also learn basic usage with examples.

What is Pexpect?

Pexpect lets you automate interactive applications. It sends inputs and reads outputs like a human would. This makes it great for testing and automation.

Common uses include SSH automation, FTP sessions, and command-line tools. It works on Linux, macOS, and Windows (with some limitations).

Install Pexpect in Python

You can install Pexpect using pip, Python's package manager. Make sure you have Python installed first.

 
pip install pexpect

For Python 3, you might need to use pip3:

 
pip3 install pexpect

If you need to install pip first, check our guide on installing Python packages.

Verify Installation

After installing, verify it works:

 
import pexpect
print(pexpect.__version__)


4.8.0

Basic Pexpect Example

Here's a simple example that runs the Unix ls command:

 
import pexpect

child = pexpect.spawn('ls -l')
child.expect(pexpect.EOF)
print(child.before.decode())

This code runs ls -l and prints the output. The expect method waits for the command to finish.

Automating SSH with Pexpect

Pexpect is great for SSH automation. Here's how to log in to a remote server:

 
import pexpect

child = pexpect.spawn('ssh user@hostname')
child.expect('password:')
child.sendline('your_password')
child.expect(pexpect.EOF)
print(child.before.decode())

This script automates an SSH login. It waits for the password prompt, then sends the password.

Handling Timeouts

Pexpect operations can timeout. Always handle timeouts in your code:

 
try:
    child.expect('pattern', timeout=5)
except pexpect.TIMEOUT:
    print("Operation timed out")

The timeout parameter sets how long to wait. The example shows basic timeout handling.

Common Pexpect Methods

Here are key Pexpect methods you'll use:

  • spawn() - Starts a new process
  • expect() - Waits for output pattern
  • sendline() - Sends input with newline
  • before - Contains output before match

For more complex automation, check our guide on R and Python integration.

Pexpect vs Other Tools

Pexpect is similar to other automation tools. Here's how it compares:

  • Paramiko - Better for pure SSH (see Paramiko guide)
  • Fabric - Higher-level SSH automation
  • Subprocess - Built-in but less interactive

Conclusion

Pexpect is powerful for automating command-line tools. It's easy to install with pip and simple to use.

You can automate SSH, FTP, and other interactive apps. Remember to handle timeouts and errors in your scripts.

For web automation, consider Bottle framework or other Python tools.