pexpect

Table of Contents

Overview

# Specify encoding='utf-8' for Python 3
child = pexpect.spawn('some_command', encoding='utf-8')
# options can be specified both in the constructoror just assigning properties
child.timeout = None        # default is 30s, timout between expect() calls
child.logfile = sys.stdout  # All input and output will be copied to this
child.expect('things')
child.send('things')
# I couldn't find somewhere explicitly documented,
# but it seems like a good thing to call close() explicitly.
child.close()
print(child.exitstatus, child.signalstatus)

run

pexpect.run(command, timeout=30, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None, **kwargs)
import pexpect
pexpect.run('scp foo user@example.com:.', events={'(?i)password': mypassword})

spawn

spawn
class pexpect.spawn(command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None, ignore_sighup=False, echo=True, preexec_fn=None, encoding=None, codec_errors='strict', dimensions=None)
child = pexpect.spawn('/usr/bin/ftp')
child = pexpect.spawn('/usr/bin/ssh user@example.com')
child = pexpect.spawn('ls -latr /tmp')
child = pexpect.spawn('/usr/bin/ftp', [])
child = pexpect.spawn('/usr/bin/ssh', ['user@example.com'])
child = pexpect.spawn('ls', ['-latr', '/tmp'])
child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')
child.expect(pexpect.EOF)
expect
expect(pattern, timeout=-1, searchwindowsize=-1, async_=False, **kw)
# the input is 'foobar'
index = p.expect(['bar', 'foo', 'foobar'])
# returns 1('foo') even though 'foobar' is a "better" match

index = p.expect(['foobar', 'foo'])
# returns 0('foobar') if all input is available at once,
# but returs 1('foo') if parts of the final 'bar' arrive late
sendline(s='')
sendcontrol(char)
close(force=True)

If you wish to get the exit status of the child you must call the close() method.