Using Pexpect
“Pexpect is a pure Python module for spawning child applications; controlling them; and responding to expected patterns in their output. Pexpect works like Don Libes’ Expect. Pexpect allows your script to spawn a child application and control it as if a human were typing commands.”
– https://pypi.org/project/pexpect/ (the project home page).
Documentation
https://pexpect.readthedocs.io/en/stable/
API Overview
https://pexpect.readthedocs.io/en/stable/overview.html
Basic usage example from the site:
# This connects to the openbsd ftp site and # downloads the recursive directory listing. import pexpect child = pexpect.spawn('ftp ftp.openbsd.org') child.expect('Name .*: ') child.sendline('anonymous') child.expect('Password:') child.sendline('[email protected]') child.expect('ftp> ') child.sendline('lcd /tmp') child.expect('ftp> ') child.sendline('cd pub/OpenBSD') child.expect('ftp> ') child.sendline('get README') child.expect('ftp> ') child.sendline('bye')
See the page linked above for more examples, particularly returning control to the user.