pexpect
Table of Contents
Overview
- Pexpect makes Python a better tool for controlling other applications.
- Pexpect can be used for automating interactive applications
# 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)
- This function runs the given command; waits for it to finish;
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'])
- Pexpect does NOT interpret shell meta characters such as redirect, pipe, or wild cards (
>
,|
, or*
) - To use those things, use one of the shell commands explicitly
- expect
expect(pattern, timeout=-1, searchwindowsize=-1, async_=False, **kw)
- This seeks through the stream until a pattern is matched.
# 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='')
Wraps
send()
, sending string s to child process, withos.linesep
automatically appended.- sendcontrol ::
sendcontrol(char)
close(force=True)
If you wish to get the exit status of the child you must call the
close()
method.