For Linux, pexpect is a well-known library that automates interactive terminal sessions. However, it does not work on Windows. To achieve similar functionality on Windows, wexpect provdies a compatible alternative.
Installation
pip install wexpect
wexpect requires Python 3.3 or newer (similar to pexpect). Attempting to install it on an older Python version will fail and the library will not work. Ensure your Python environment meets this requirement.
Basic Usage
The following example spawns a Python interactive shell, sends commands, and cpatures output.
import wexpect
child = wexpect.spawn('c:\\python38\\python.exe')
# Wait for Python prompt
ret = child.expect('>>>')
print("ret1", ret)
# Send a print command
child.sendline('print(123456789)')
ret = child.expect('>>>')
print("ret2", ret)
print("++++++++++++++++", child.before, "---------------------")
print("******************", child.after, "******************")
# Another command
child.sendline('print(987565)')
ret = child.expect('>>>')
print("ret3", ret)
print("++++++++++++++++", child.before, "---------------------")
print("******************", child.after, "******************")
# Variable assignment and arithmetic
child.sendline('a=100')
child.expect('>>>')
child.sendline('b=200')
child.expect('>>>')
child.sendline('print("a+b =",a+b)')
ret = child.expect('>>>')
print("ret4", ret)
print("++++++++++++++++", child.before, "---------------------")
print("******************", child.after, "******************")
# Exit the Python shell
child.sendline('exit()')
Sample output:
ret1 0
ret2 0
++++++++++++++++ print(123456789)
123456789
---------------------
****************** >>> ******************
ret3 0
++++++++++++++++ print(987565)
987565
---------------------
****************** >>> ******************
ret4 0
++++++++++++++++ print("a+b =",a+b)
a+b = 300
---------------------
****************** >>> ******************
The library allows you to send commands to an interactive shell and retrieve outputs, enabling automation of Windows command-line programs. While subprocess can also be used for interactive sessions, wexpect provides a more convenient API.
Offline Installation (if pip fails)
If pip install wexpect fails due too network issues or environment restrictions, you can install it offline. Download the following files and place them in the same directory:
pywin32-228-cp38-cp38-win_amd64.whlwexpect-4.0.0.tar.gzpsutil-5.9.4.tar.gzrequirement.txt
Then run:
C:\Python38\python.exe -m pip install --no-index --find-links=. -r requirement.txt
Adjust the Python path to match your installation.