1
'''Pexpect is a Python module for spawning child applications and controlling
2
them automatically. Pexpect can be used for automating interactive applications
3
such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
4
scripts for duplicating software package installations on different servers. It
5
can be used for automated software testing. Pexpect is in the spirit of Don
6
Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
7
require TCL and Expect or require C extensions to be compiled. Pexpect does not
8
use C, Expect, or TCL extensions. It should work on any platform that supports
9
the standard Python pty module. The Pexpect interface focuses on ease of use so
10
that simple tasks are easy.
12
There are two main interfaces to the Pexpect system; these are the function,
13
run() and the class, spawn. The spawn class is more powerful. The run()
14
function is simpler than spawn, and is good for quickly calling program. When
15
you call the run() function it executes a given program and then returns the
16
output. This is a handy replacement for os.system().
22
The spawn class is the more powerful interface to the Pexpect system. You can
23
use this to spawn a child program then interact with it by sending input and
24
expecting responses (waiting for patterns in the child's output).
28
child = pexpect.spawn('scp foo user@example.com:.')
29
child.expect('Password:')
30
child.sendline(mypassword)
32
This works even for commands that ask for passwords or other input outside of
33
the normal stdio streams. For example, ssh reads input directly from the TTY
34
device which bypasses stdin.
36
Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
37
Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
38
vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
39
Jacques-Etienne Baudoux, Geoffrey Marshall, Francisco Lourenco, Glen Mabey,
40
Karthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume
41
Chazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn, John
42
Spiegel, Jan Grant, and Shane Kerr. Let me know if I forgot anyone.
44
Pexpect is free, open source, and all that good stuff.
45
http://pexpect.sourceforge.net/
49
This license is approved by the OSI and FSF as GPL-compatible.
50
http://opensource.org/licenses/isc-license.txt
52
Copyright (c) 2012, Noah Spurrier <noah@noah.org>
53
PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
54
PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
55
COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
56
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
57
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
58
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
59
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
60
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
61
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
62
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
83
except ImportError: # pragma: no cover
84
err = sys.exc_info()[1]
85
raise ImportError(str(err) + '''
87
A critical module was not found. Probably this operating system does not
88
support it. Pexpect is intended for UNIX-like operating systems.''')
92
__all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnu', 'run', 'runu',
93
'which', 'split_command_line', '__version__', '__revision__']
95
PY3 = (sys.version_info[0] >= 3)
97
# Exception classes used by this module.
98
class ExceptionPexpect(Exception):
99
'''Base class for all exceptions raised by this module.
102
def __init__(self, value):
106
return str(self.value)
109
'''This returns an abbreviated stack trace with lines that only concern
110
the caller. In other words, the stack trace inside the Pexpect module
113
tblist = traceback.extract_tb(sys.exc_info()[2])
114
tblist = [item for item in tblist if 'pexpect/__init__' not in item[0]]
115
tblist = traceback.format_list(tblist)
116
return ''.join(tblist)
119
class EOF(ExceptionPexpect):
120
'''Raised when EOF is read from a child.
121
This usually means the child has exited.'''
124
class TIMEOUT(ExceptionPexpect):
125
'''Raised when a read time exceeds the timeout. '''
127
##class TIMEOUT_PATTERN(TIMEOUT):
128
## '''Raised when the pattern match time exceeds the timeout.
129
## This is different than a read TIMEOUT because the child process may
130
## give output, thus never give a TIMEOUT, but the output
131
## may never match a pattern.
133
##class MAXBUFFER(ExceptionPexpect):
134
## '''Raised when a buffer fills before matching an expected pattern.'''
137
def run(command, timeout=-1, withexitstatus=False, events=None,
138
extra_args=None, logfile=None, cwd=None, env=None):
141
This function runs the given command; waits for it to finish; then
142
returns all output as a string. STDERR is included in output. If the full
143
path to the command is not given then the path is searched.
145
Note that lines are terminated by CR/LF (\\r\\n) combination even on
146
UNIX-like systems because this is the standard for pseudottys. If you set
147
'withexitstatus' to true, then run will return a tuple of (command_output,
148
exitstatus). If 'withexitstatus' is false then this returns just
151
The run() function can often be used instead of creating a spawn instance.
152
For example, the following code uses spawn::
154
from pexpect import *
155
child = spawn('scp foo user@example.com:.')
156
child.expect('(?i)password')
157
child.sendline(mypassword)
159
The previous code can be replace with the following::
161
from pexpect import *
162
run('scp foo user@example.com:.', events={'(?i)password': mypassword})
166
Start the apache daemon on the local machine::
168
from pexpect import *
169
run("/usr/local/apache/bin/apachectl start")
171
Check in a file using SVN::
173
from pexpect import *
174
run("svn ci -m 'automatic commit' my_file.py")
176
Run a command and capture exit status::
178
from pexpect import *
179
(command_output, exitstatus) = run('ls -l /bin', withexitstatus=1)
181
The following will run SSH and execute 'ls -l' on the remote machine. The
182
password 'secret' will be sent if the '(?i)password' pattern is ever seen::
184
run("ssh username@machine.example.com 'ls -l'",
185
events={'(?i)password':'secret\\n'})
187
This will start mencoder to rip a video from DVD. This will also display
188
progress ticks every 5 seconds as it runs. For example::
190
from pexpect import *
192
print d['event_count'],
193
run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
194
events={TIMEOUT:print_ticks}, timeout=5)
196
The 'events' argument should be a dictionary of patterns and responses.
197
Whenever one of the patterns is seen in the command out run() will send the
198
associated response string. Note that you should put newlines in your
199
string if Enter is necessary. The responses may also contain callback
200
functions. Any callback is function that takes a dictionary as an argument.
201
The dictionary contains all the locals from the run() function, so you can
202
access the child spawn object or any other variable defined in run()
203
(event_count, child, and extra_args are the most useful). A callback may
204
return True to stop the current run process otherwise run() continues until
205
the next event. A callback may also return a string which will be sent to
206
the child. 'extra_args' is not used by directly run(). It provides a way to
207
pass data to a callback function through run() through the locals
208
dictionary passed to a callback.
210
return _run(command, timeout=timeout, withexitstatus=withexitstatus,
211
events=events, extra_args=extra_args, logfile=logfile, cwd=cwd,
212
env=env, _spawn=spawn)
214
def runu(command, timeout=-1, withexitstatus=False, events=None,
215
extra_args=None, logfile=None, cwd=None, env=None, **kwargs):
216
"""This offers the same interface as :func:`run`, but using unicode.
218
Like :class:`spawnu`, you can pass ``encoding`` and ``errors`` parameters,
219
which will be used for both input and output.
221
return _run(command, timeout=timeout, withexitstatus=withexitstatus,
222
events=events, extra_args=extra_args, logfile=logfile, cwd=cwd,
223
env=env, _spawn=spawnu, **kwargs)
225
def _run(command, timeout, withexitstatus, events, extra_args, logfile, cwd,
226
env, _spawn, **kwargs):
228
child = _spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env,
231
child = _spawn(command, timeout=timeout, maxread=2000, logfile=logfile,
232
cwd=cwd, env=env, **kwargs)
233
if events is not None:
234
patterns = list(events.keys())
235
responses = list(events.values())
237
# This assumes EOF or TIMEOUT will eventually cause run to terminate.
240
child_result_list = []
244
index = child.expect(patterns)
245
if isinstance(child.after, child.allowed_string_types):
246
child_result_list.append(child.before + child.after)
248
# child.after may have been a TIMEOUT or EOF,
249
# which we don't want appended to the list.
250
child_result_list.append(child.before)
251
if isinstance(responses[index], child.allowed_string_types):
252
child.send(responses[index])
253
elif isinstance(responses[index], types.FunctionType):
254
callback_result = responses[index](locals())
256
if isinstance(callback_result, child.allowed_string_types):
257
child.send(callback_result)
258
elif callback_result:
261
raise TypeError('The callback must be a string or function.')
262
event_count = event_count + 1
264
child_result_list.append(child.before)
267
child_result_list.append(child.before)
269
child_result = child.string_type().join(child_result_list)
272
return (child_result, child.exitstatus)
277
'''This is the main class interface for Pexpect. Use this class to start
278
and control child applications. '''
281
allowed_string_types = (bytes, str)
285
linesep = os.linesep.encode('ascii')
286
write_to_stdout = sys.stdout.buffer.write
288
allowed_string_types = (basestring,) # analysis:ignore
289
_chr = staticmethod(chr)
291
write_to_stdout = sys.stdout.write
295
def __init__(self, command, args=[], timeout=30, maxread=2000,
296
searchwindowsize=None, logfile=None, cwd=None, env=None,
299
'''This is the constructor. The command parameter may be a string that
300
includes a command and any arguments to the command. For example::
302
child = pexpect.spawn('/usr/bin/ftp')
303
child = pexpect.spawn('/usr/bin/ssh user@example.com')
304
child = pexpect.spawn('ls -latr /tmp')
306
You may also construct it with a list of arguments like so::
308
child = pexpect.spawn('/usr/bin/ftp', [])
309
child = pexpect.spawn('/usr/bin/ssh', ['user@example.com'])
310
child = pexpect.spawn('ls', ['-latr', '/tmp'])
312
After this the child application will be created and will be ready to
313
talk to. For normal use, see expect() and send() and sendline().
315
Remember that Pexpect does NOT interpret shell meta characters such as
316
redirect, pipe, or wild cards (``>``, ``|``, or ``*``). This is a
317
common mistake. If you want to run a command and pipe it through
318
another command then you must also start a shell. For example::
320
child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')
321
child.expect(pexpect.EOF)
323
The second form of spawn (where you pass a list of arguments) is useful
324
in situations where you wish to spawn a command and pass it its own
325
argument list. This can make syntax more clear. For example, the
326
following is equivalent to the previous example::
328
shell_cmd = 'ls -l | grep LOG > logs.txt'
329
child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
330
child.expect(pexpect.EOF)
332
The maxread attribute sets the read buffer size. This is maximum number
333
of bytes that Pexpect will try to read from a TTY at one time. Setting
334
the maxread size to 1 will turn off buffering. Setting the maxread
335
value higher may help performance in cases where large amounts of
336
output are read back from the child. This feature is useful in
337
conjunction with searchwindowsize.
339
The searchwindowsize attribute sets the how far back in the incoming
340
seach buffer Pexpect will search for pattern matches. Every time
341
Pexpect reads some data from the child it will append the data to the
342
incoming buffer. The default is to search from the beginning of the
343
incoming buffer each time new data is read from the child. But this is
344
very inefficient if you are running a command that generates a large
345
amount of data where you want to match. The searchwindowsize does not
346
affect the size of the incoming data buffer. You will still have
347
access to the full buffer after expect() returns.
349
The logfile member turns on or off logging. All input and output will
350
be copied to the given file object. Set logfile to None to stop
351
logging. This is the default. Set logfile to sys.stdout to echo
352
everything to standard output. The logfile is flushed after each write.
354
Example log input and output to a file::
356
child = pexpect.spawn('some_command')
357
fout = file('mylog.txt','w')
360
Example log to stdout::
362
child = pexpect.spawn('some_command')
363
child.logfile = sys.stdout
365
The logfile_read and logfile_send members can be used to separately log
366
the input from the child and output sent to the child. Sometimes you
367
don't want to see everything you write to the child. You only want to
368
log what the child sends back. For example::
370
child = pexpect.spawn('some_command')
371
child.logfile_read = sys.stdout
373
To separately log output sent to the child use logfile_send::
375
self.logfile_send = fout
377
If ``ignore_sighup`` is True, the child process will ignore SIGHUP
378
signals. For now, the default is True, to preserve the behaviour of
379
earlier versions of Pexpect, but you should pass this explicitly if you
382
The delaybeforesend helps overcome a weird behavior that many users
383
were experiencing. The typical problem was that a user would expect() a
384
"Password:" prompt and then immediately call sendline() to send the
385
password. The user would then see that their password was echoed back
386
to them. Passwords don't normally echo. The problem is caused by the
387
fact that most applications print out the "Password" prompt and then
388
turn off stdin echo, but if you send your password before the
389
application turned off echo, then you get your password echoed.
390
Normally this wouldn't be a problem when interacting with a human at a
391
real keyboard. If you introduce a slight delay just before writing then
392
this seems to clear up the problem. This was such a common problem for
393
many users that I decided that the default pexpect behavior should be
394
to sleep just before writing to the child application. 1/20th of a
395
second (50 ms) seems to be enough to clear up the problem. You can set
396
delaybeforesend to 0 to return to the old behavior. Most Linux machines
397
don't like this to be below 0.03. I don't know why.
399
Note that spawn is clever about finding commands on your path.
400
It uses the same logic that "which" uses to find executables.
402
If you wish to get the exit status of the child you must call the
403
close() method. The exit or signal status of the child will be stored
404
in self.exitstatus or self.signalstatus. If the child exited normally
405
then exitstatus will store the exit return code and signalstatus will
406
be None. If the child was terminated abnormally with a signal then
407
signalstatus will store the signal value and exitstatus will be None.
408
If you need more detail you can also read the self.status member which
409
stores the status returned by os.waitpid. You can interpret this using
410
os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. '''
412
self.STDIN_FILENO = pty.STDIN_FILENO
413
self.STDOUT_FILENO = pty.STDOUT_FILENO
414
self.STDERR_FILENO = pty.STDERR_FILENO
415
self.stdin = sys.stdin
416
self.stdout = sys.stdout
417
self.stderr = sys.stderr
420
self.ignorecase = False
424
self.match_index = None
425
self.terminated = True
426
self.exitstatus = None
427
self.signalstatus = None
428
# status returned by os.waitpid
430
self.flag_eof = False
432
# the chile filedescriptor is initially closed
434
self.timeout = timeout
436
self.logfile = logfile
437
# input from child (read_nonblocking)
438
self.logfile_read = None
439
# output to send (send, sendline)
440
self.logfile_send = None
441
# max bytes to read at one time into buffer
442
self.maxread = maxread
443
# This is the read buffer. See maxread.
444
self.buffer = self.string_type()
445
# Data before searchwindowsize point is preserved, but not searched.
446
self.searchwindowsize = searchwindowsize
447
# Delay used before sending data to child. Time in seconds.
448
# Most Linux machines don't like this to be below 0.03 (30 ms).
449
self.delaybeforesend = 0.05
450
# Used by close() to give kernel time to update process status.
452
self.delayafterclose = 0.1
453
# Used by terminate() to give kernel time to update process status.
455
self.delayafterterminate = 0.1
456
self.softspace = False
457
self.name = '<' + repr(self) + '>'
461
self.ignore_sighup = ignore_sighup
462
# This flags if we are running on irix
463
self.__irix_hack = (sys.platform.lower().find('irix') >= 0)
464
# Solaris uses internal __fork_pty(). All others use pty.fork().
465
if ((sys.platform.lower().find('solaris') >= 0)
466
or (sys.platform.lower().find('sunos5') >= 0)):
467
self.use_native_pty_fork = False
469
self.use_native_pty_fork = True
471
# Support subclasses that do not use command or args.
475
self.name = '<pexpect factory incomplete>'
477
self._spawn(command, args)
480
def _coerce_expect_string(s):
481
if not isinstance(s, bytes):
482
return s.encode('ascii')
486
def _coerce_send_string(s):
487
if not isinstance(s, bytes):
488
return s.encode('utf-8')
492
def _coerce_read_string(s):
496
'''This makes sure that no system resources are left open. Python only
497
garbage collects Python objects. OS file descriptors are not Python
498
objects, so they must be handled explicitly. If the child file
499
descriptor was opened outside of this class (passed to the constructor)
500
then this does not close it. '''
503
# It is possible for __del__ methods to execute during the
504
# teardown of the Python VM itself. Thus self.close() may
505
# trigger an exception because os.close may be None.
508
# which exception, shouldnt' we catch explicitly .. ?
513
'''This returns a human-readable string that represents the state of
518
s.append('version: ' + __version__)
519
s.append('command: ' + str(self.command))
520
s.append('args: %r' % (self.args,))
521
s.append('searcher: %r' % (self.searcher,))
522
s.append('buffer (last 100 chars): %r' % (self.buffer)[-100:],)
523
s.append('before (last 100 chars): %r' % (self.before)[-100:],)
524
s.append('after: %r' % (self.after,))
525
s.append('match: %r' % (self.match,))
526
s.append('match_index: ' + str(self.match_index))
527
s.append('exitstatus: ' + str(self.exitstatus))
528
s.append('flag_eof: ' + str(self.flag_eof))
529
s.append('pid: ' + str(self.pid))
530
s.append('child_fd: ' + str(self.child_fd))
531
s.append('closed: ' + str(self.closed))
532
s.append('timeout: ' + str(self.timeout))
533
s.append('delimiter: ' + str(self.delimiter))
534
s.append('logfile: ' + str(self.logfile))
535
s.append('logfile_read: ' + str(self.logfile_read))
536
s.append('logfile_send: ' + str(self.logfile_send))
537
s.append('maxread: ' + str(self.maxread))
538
s.append('ignorecase: ' + str(self.ignorecase))
539
s.append('searchwindowsize: ' + str(self.searchwindowsize))
540
s.append('delaybeforesend: ' + str(self.delaybeforesend))
541
s.append('delayafterclose: ' + str(self.delayafterclose))
542
s.append('delayafterterminate: ' + str(self.delayafterterminate))
545
def _spawn(self, command, args=[]):
546
'''This starts the given command in a child process. This does all the
547
fork/exec type of stuff for a pty. This is called by __init__. If args
548
is empty then command will be parsed (split on spaces) and args will be
549
set to parsed arguments. '''
551
# The pid and child_fd of this object get set by this method.
552
# Note that it is difficult for this method to fail.
553
# You cannot detect if the child process cannot start.
554
# So the only way you can tell if the child process started
555
# or not is to try to read from the file descriptor. If you get
556
# EOF immediately then it means that the child is already dead.
557
# That may not necessarily be bad because you may have spawned a child
558
# that performs some task; creates no stdout output; and then dies.
560
# If command is an int type then it may represent a file descriptor.
561
if isinstance(command, type(0)):
562
raise ExceptionPexpect('Command is an int type. ' +
563
'If this is a file descriptor then maybe you want to ' +
564
'use fdpexpect.fdspawn which takes an existing ' +
565
'file descriptor instead of a command string.')
567
if not isinstance(args, type([])):
568
raise TypeError('The argument, args, must be a list.')
571
self.args = split_command_line(command)
572
self.command = self.args[0]
574
# Make a shallow copy of the args list.
576
self.args.insert(0, command)
577
self.command = command
579
command_with_path = which(self.command)
580
if command_with_path is None:
581
raise ExceptionPexpect('The command was not found or was not ' +
582
'executable: %s.' % self.command)
583
self.command = command_with_path
584
self.args[0] = self.command
586
self.name = '<' + ' '.join(self.args) + '>'
588
assert self.pid is None, 'The pid member must be None.'
589
assert self.command is not None, 'The command member must not be None.'
591
if self.use_native_pty_fork:
593
self.pid, self.child_fd = pty.fork()
595
err = sys.exc_info()[1]
596
raise ExceptionPexpect('pty.fork() failed: ' + str(err))
598
# Use internal __fork_pty
599
self.pid, self.child_fd = self.__fork_pty()
604
# used by setwinsize()
605
self.child_fd = sys.stdout.fileno()
606
self.setwinsize(24, 80)
607
# which exception, shouldnt' we catch explicitly .. ?
609
# Some platforms do not like setwinsize (Cygwin).
610
# This will cause problem when running applications that
611
# are very picky about window size.
612
# This is a serious limitation, but not a show stopper.
614
# Do not allow child to inherit open file descriptors from parent.
615
max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
616
for i in range(3, max_fd):
622
if self.ignore_sighup:
623
signal.signal(signal.SIGHUP, signal.SIG_IGN)
625
if self.cwd is not None:
628
os.execv(self.command, self.args)
630
os.execvpe(self.command, self.args, self.env)
633
self.terminated = False
636
def __fork_pty(self):
637
'''This implements a substitute for the forkpty system call. This
638
should be more portable than the pty.fork() function. Specifically,
639
this should work on Solaris.
641
Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
642
resolve the issue with Python's pty.fork() not supporting Solaris,
643
particularly ssh. Based on patch to posixmodule.c authored by Noah
646
http://mail.python.org/pipermail/python-dev/2003-May/035281.html
650
parent_fd, child_fd = os.openpty()
651
if parent_fd < 0 or child_fd < 0:
652
raise ExceptionPexpect("Could not open with os.openpty().")
656
raise ExceptionPexpect("Failed os.fork().")
660
self.__pty_make_controlling_tty(child_fd)
672
return pid, parent_fd
674
def __pty_make_controlling_tty(self, tty_fd):
675
'''This makes the pseudo-terminal the controlling tty. This should be
676
more portable than the pty.fork() function. Specifically, this should
679
child_name = os.ttyname(tty_fd)
681
# Disconnect from controlling tty. Harmless if not already connected.
683
fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
686
# which exception, shouldnt' we catch explicitly .. ?
688
# Already disconnected. This happens if running inside cron.
693
# Verify we are disconnected from controlling tty
694
# by attempting to open it again.
696
fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
699
raise ExceptionPexpect('Failed to disconnect from ' +
700
'controlling tty. It is still possible to open /dev/tty.')
701
# which exception, shouldnt' we catch explicitly .. ?
703
# Good! We are disconnected from a controlling tty.
706
# Verify we can open child pty.
707
fd = os.open(child_name, os.O_RDWR)
709
raise ExceptionPexpect("Could not open child pty, " + child_name)
713
# Verify we now have a controlling tty.
714
fd = os.open("/dev/tty", os.O_WRONLY)
716
raise ExceptionPexpect("Could not open controlling tty, /dev/tty")
721
'''This returns the file descriptor of the pty for the child.
725
def close(self, force=True):
726
'''This closes the connection with the child application. Note that
727
calling close() more than once is valid. This emulates standard Python
728
behavior with files. Set force to True if you want to make sure that
729
the child is terminated (SIGKILL is sent if the child ignores SIGHUP
734
os.close(self.child_fd)
735
# Give kernel time to update process status.
736
time.sleep(self.delayafterclose)
738
if not self.terminate(force):
739
raise ExceptionPexpect('Could not terminate the child.')
745
'''This does nothing. It is here to support the interface for a
746
File-like object. '''
751
'''This returns True if the file descriptor is open and connected to a
752
tty(-like) device, else False. '''
754
return os.isatty(self.child_fd)
756
def waitnoecho(self, timeout=-1):
757
'''This waits until the terminal ECHO flag is set False. This returns
758
True if the echo mode is off. This returns False if the ECHO flag was
759
not set False before the timeout. This can be used to detect when the
760
child is waiting for a password. Usually a child application will turn
761
off echo mode when it is waiting for the user to enter a password. For
762
example, instead of expecting the "password:" prompt you can wait for
763
the child to set ECHO off::
765
p = pexpect.spawn('ssh user@example.com')
767
p.sendline(mypassword)
769
If timeout==-1 then this method will use the value in self.timeout.
770
If timeout==None then this method to block until ECHO flag is False.
774
timeout = self.timeout
775
if timeout is not None:
776
end_time = time.time() + timeout
778
if not self.getecho():
780
if timeout < 0 and timeout is not None:
782
if timeout is not None:
783
timeout = end_time - time.time()
787
'''This returns the terminal echo mode. This returns True if echo is
788
on or False if echo is off. Child applications that are expecting you
789
to enter a password often set ECHO False. See waitnoecho(). '''
791
attr = termios.tcgetattr(self.child_fd)
792
if attr[3] & termios.ECHO:
796
def setecho(self, state):
797
'''This sets the terminal echo mode on or off. Note that anything the
798
child sent before the echo will be lost, so you should be sure that
799
your input buffer is empty before you call setecho(). For example, the
800
following will work as expected::
802
p = pexpect.spawn('cat') # Echo is on by default.
803
p.sendline('1234') # We expect see this twice from the child...
804
p.expect(['1234']) # ... once from the tty echo...
805
p.expect(['1234']) # ... and again from cat itself.
806
p.setecho(False) # Turn off tty echo
807
p.sendline('abcd') # We will set this only once (echoed by cat).
808
p.sendline('wxyz') # We will set this only once (echoed by cat)
812
The following WILL NOT WORK because the lines sent before the setecho
815
p = pexpect.spawn('cat')
817
p.setecho(False) # Turn off tty echo
818
p.sendline('abcd') # We will set this only once (echoed by cat).
819
p.sendline('wxyz') # We will set this only once (echoed by cat)
827
attr = termios.tcgetattr(self.child_fd)
829
attr[3] = attr[3] | termios.ECHO
831
attr[3] = attr[3] & ~termios.ECHO
832
# I tried TCSADRAIN and TCSAFLUSH, but
833
# these were inconsistent and blocked on some platforms.
834
# TCSADRAIN would probably be ideal if it worked.
835
termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
837
def _log(self, s, direction):
838
if self.logfile is not None:
839
self.logfile.write(s)
841
second_log = self.logfile_send if (direction=='send') else self.logfile_read
842
if second_log is not None:
846
def read_nonblocking(self, size=1, timeout=-1):
847
'''This reads at most size characters from the child application. It
848
includes a timeout. If the read does not complete within the timeout
849
period then a TIMEOUT exception is raised. If the end of file is read
850
then an EOF exception will be raised. If a log file was set using
851
setlog() then all data will also be written to the log file.
853
If timeout is None then the read may block indefinitely.
854
If timeout is -1 then the self.timeout value is used. If timeout is 0
855
then the child is polled and if there is no data immediately ready
856
then this will raise a TIMEOUT exception.
858
The timeout refers only to the amount of time to read at least one
859
character. This is not effected by the 'size' parameter, so if you call
860
read_nonblocking(size=100, timeout=30) and only one character is
861
available right away then one character will be returned immediately.
862
It will not wait for 30 seconds for another 99 characters to come in.
864
This is a wrapper around os.read(). It uses select.select() to
865
implement the timeout. '''
868
raise ValueError('I/O operation on closed file.')
871
timeout = self.timeout
873
# Note that some systems such as Solaris do not give an EOF when
874
# the child dies. In fact, you can still try to read
875
# from the child_fd -- it will block forever or until TIMEOUT.
876
# For this case, I test isalive() before doing any reading.
877
# If isalive() is false, then I pretend that this is the same as EOF.
878
if not self.isalive():
879
# timeout of 0 means "poll"
880
r, w, e = self.__select([self.child_fd], [], [], 0)
883
raise EOF('End Of File (EOF). Braindead platform.')
884
elif self.__irix_hack:
885
# Irix takes a long time before it realizes a child was terminated.
886
# FIXME So does this mean Irix systems are forced to always have
887
# FIXME a 2 second delay when calling read_nonblocking? That sucks.
888
r, w, e = self.__select([self.child_fd], [], [], 2)
889
if not r and not self.isalive():
891
raise EOF('End Of File (EOF). Slow platform.')
893
r, w, e = self.__select([self.child_fd], [], [], timeout)
896
if not self.isalive():
897
# Some platforms, such as Irix, will claim that their
898
# processes are alive; timeout on the select; and
899
# then finally admit that they are not alive.
901
raise EOF('End of File (EOF). Very slow platform.')
903
raise TIMEOUT('Timeout exceeded.')
905
if self.child_fd in r:
907
s = os.read(self.child_fd, size)
911
raise EOF('End Of File (EOF). Exception style platform.')
915
raise EOF('End Of File (EOF). Empty string style platform.')
917
s = self._coerce_read_string(s)
921
raise ExceptionPexpect('Reached an unexpected state.')
923
def read(self, size=-1):
924
'''This reads at most "size" bytes from the file (less if the read hits
925
EOF before obtaining size bytes). If the size argument is negative or
926
omitted, read all data until EOF is reached. The bytes are returned as
927
a string object. An empty string is returned when EOF is encountered
931
return self.string_type()
933
# delimiter default is EOF
934
self.expect(self.delimiter)
937
# I could have done this more directly by not using expect(), but
938
# I deliberately decided to couple read() to expect() so that
939
# I would catch any bugs early and ensure consistant behavior.
940
# It's a little less efficient, but there is less for me to
941
# worry about if I have to later modify read() or expect().
942
# Note, it's OK if size==-1 in the regex. That just means it
943
# will never match anything in which case we stop only on EOF.
944
cre = re.compile(self._coerce_expect_string('.{%d}' % size), re.DOTALL)
945
# delimiter default is EOF
946
index = self.expect([cre, self.delimiter])
948
### FIXME self.before should be ''. Should I assert this?
952
def readline(self, size=-1):
953
'''This reads and returns one entire line. The newline at the end of
954
line is returned as part of the string, unless the file ends without a
955
newline. An empty string is returned if EOF is encountered immediately.
956
This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
957
this is what the pseudotty device returns. So contrary to what you may
958
expect you will receive newlines as \\r\\n.
960
If the size argument is 0 then an empty string is returned. In all
961
other cases the size argument is ignored, which is not standard
962
behavior for a file-like object. '''
965
return self.string_type()
966
# delimiter default is EOF
967
index = self.expect([b'\r\n', self.delimiter])
969
return self.before + b'\r\n'
974
'''This is to support iterators over a file-like object.
976
return iter(self.readline, self.string_type())
978
def readlines(self, sizehint=-1):
979
'''This reads until EOF using readline() and returns a list containing
980
the lines thus read. The optional 'sizehint' argument is ignored.
981
Remember, because this reads until EOF that means the child
982
process should have closed its stdout. If you run this method on
983
a child that is still running with its stdout open then this
984
method will block until it timesout.'''
988
line = self.readline()
995
'''This is similar to send() except that there is no return value.
1000
def writelines(self, sequence):
1001
'''This calls write() for each element in the sequence. The sequence
1002
can be any iterable object producing strings, typically a list of
1003
strings. This does not add line separators. There is no return value.
1010
'''Sends string ``s`` to the child process, returning the number of
1011
bytes written. If a logfile is specified, a copy is written to that
1014
time.sleep(self.delaybeforesend)
1016
s = self._coerce_send_string(s)
1017
self._log(s, 'send')
1019
return self._send(s)
1022
return os.write(self.child_fd, s)
1024
def sendline(self, s=''):
1025
'''Wraps send(), sending string ``s`` to child process, with os.linesep
1026
automatically appended. Returns number of bytes written. '''
1029
n = n + self.send(self.linesep)
1032
def sendcontrol(self, char):
1034
'''Helper method that wraps send() with mnemonic access for sending control
1035
character to the child (such as Ctrl-C or Ctrl-D). For example, to send
1036
Ctrl-G (ASCII 7, bell, '\a')::
1038
child.sendcontrol('g')
1040
See also, sendintr() and sendeof().
1045
if a >= 97 and a <= 122:
1046
a = a - ord('a') + 1
1047
return self.send(self._chr(a))
1048
d = {'@': 0, '`': 0,
1057
return self.send(self._chr(d[char]))
1061
'''This sends an EOF to the child. This sends a character which causes
1062
the pending parent output buffer to be sent to the waiting child
1063
program without waiting for end-of-line. If it is the first character
1064
of the line, the read() in the user program returns 0, which signifies
1065
end-of-file. This means to work as expected a sendeof() has to be
1066
called at the beginning of a line. This method does not send a newline.
1067
It is the responsibility of the caller to ensure the eof is sent at the
1068
beginning of a line. '''
1070
### Hmmm... how do I send an EOF?
1071
###C if ((m = write(pty, *buf, p - *buf)) < 0)
1072
###C return (errno == EWOULDBLOCK) ? n : -1;
1073
#fd = sys.stdin.fileno()
1074
#old = termios.tcgetattr(fd) # remember current state
1075
#attr = termios.tcgetattr(fd)
1076
#attr[3] = attr[3] | termios.ICANON # ICANON must be set to see EOF
1077
#try: # use try/finally to ensure state gets restored
1078
# termios.tcsetattr(fd, termios.TCSADRAIN, attr)
1079
# if hasattr(termios, 'CEOF'):
1080
# os.write(self.child_fd, '%c' % termios.CEOF)
1082
# # Silly platform does not define CEOF so assume CTRL-D
1083
# os.write(self.child_fd, '%c' % 4)
1084
#finally: # restore state
1085
# termios.tcsetattr(fd, termios.TCSADRAIN, old)
1086
if hasattr(termios, 'VEOF'):
1087
char = ord(termios.tcgetattr(self.child_fd)[6][termios.VEOF])
1089
# platform does not define VEOF so assume CTRL-D
1091
self.send(self._chr(char))
1095
'''This sends a SIGINT to the child. It does not require
1096
the SIGINT to be the first character on a line. '''
1098
if hasattr(termios, 'VINTR'):
1099
char = ord(termios.tcgetattr(self.child_fd)[6][termios.VINTR])
1101
# platform does not define VINTR so assume CTRL-C
1103
self.send(self._chr(char))
1107
'''This returns True if the EOF exception was ever raised.
1110
return self.flag_eof
1112
def terminate(self, force=False):
1114
'''This forces a child process to terminate. It starts nicely with
1115
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
1116
returns True if the child was terminated. This returns False if the
1117
child could not be terminated. '''
1119
if not self.isalive():
1122
self.kill(signal.SIGHUP)
1123
time.sleep(self.delayafterterminate)
1124
if not self.isalive():
1126
self.kill(signal.SIGCONT)
1127
time.sleep(self.delayafterterminate)
1128
if not self.isalive():
1130
self.kill(signal.SIGINT)
1131
time.sleep(self.delayafterterminate)
1132
if not self.isalive():
1135
self.kill(signal.SIGKILL)
1136
time.sleep(self.delayafterterminate)
1137
if not self.isalive():
1143
# I think there are kernel timing issues that sometimes cause
1144
# this to happen. I think isalive() reports True, but the
1145
# process is dead to the kernel.
1146
# Make one last attempt to see if the kernel is up to date.
1147
time.sleep(self.delayafterterminate)
1148
if not self.isalive():
1155
'''This waits until the child exits. This is a blocking call. This will
1156
not read any data from the child, so this will block forever if the
1157
child has unread output and has terminated. In other words, the child
1158
may have printed output then called exit(), but, the child is
1159
technically still alive until its output is read by the parent. '''
1162
pid, status = os.waitpid(self.pid, 0)
1164
raise ExceptionPexpect('Cannot wait for dead child process.')
1165
self.exitstatus = os.WEXITSTATUS(status)
1166
if os.WIFEXITED(status):
1167
self.status = status
1168
self.exitstatus = os.WEXITSTATUS(status)
1169
self.signalstatus = None
1170
self.terminated = True
1171
elif os.WIFSIGNALED(status):
1172
self.status = status
1173
self.exitstatus = None
1174
self.signalstatus = os.WTERMSIG(status)
1175
self.terminated = True
1176
elif os.WIFSTOPPED(status):
1177
# You can't call wait() on a child process in the stopped state.
1178
raise ExceptionPexpect('Called wait() on a stopped child ' +
1179
'process. This is not supported. Is some other ' +
1180
'process attempting job control with our child pid?')
1181
return self.exitstatus
1185
'''This tests if the child process is running or not. This is
1186
non-blocking. If the child was terminated then this will read the
1187
exitstatus or signalstatus of the child. This returns True if the child
1188
process appears to be running or False if not. It can take literally
1189
SECONDS for Solaris to return the right status. '''
1195
# This is for Linux, which requires the blocking form
1196
# of waitpid to # get status of a defunct process.
1197
# This is super-lame. The flag_eof would have been set
1198
# in read_nonblocking(), so this should be safe.
1201
waitpid_options = os.WNOHANG
1204
pid, status = os.waitpid(self.pid, waitpid_options)
1206
err = sys.exc_info()[1]
1207
# No child processes
1208
if err.errno == errno.ECHILD:
1209
raise ExceptionPexpect('isalive() encountered condition ' +
1210
'where "terminated" is 0, but there was no child ' +
1211
'process. Did someone else call waitpid() ' +
1216
# I have to do this twice for Solaris.
1217
# I can't even believe that I figured this out...
1218
# If waitpid() returns 0 it means that no child process
1219
# wishes to report, and the value of status is undefined.
1222
### os.WNOHANG) # Solaris!
1223
pid, status = os.waitpid(self.pid, waitpid_options)
1224
except OSError as e:
1225
# This should never happen...
1226
if e.errno == errno.ECHILD:
1227
raise ExceptionPexpect('isalive() encountered condition ' +
1228
'that should never happen. There was no child ' +
1229
'process. Did someone else call waitpid() ' +
1234
# If pid is still 0 after two calls to waitpid() then the process
1235
# really is alive. This seems to work on all platforms, except for
1236
# Irix which seems to require a blocking call on waitpid or select,
1237
# so I let read_nonblocking take care of this situation
1238
# (unfortunately, this requires waiting through the timeout).
1245
if os.WIFEXITED(status):
1246
self.status = status
1247
self.exitstatus = os.WEXITSTATUS(status)
1248
self.signalstatus = None
1249
self.terminated = True
1250
elif os.WIFSIGNALED(status):
1251
self.status = status
1252
self.exitstatus = None
1253
self.signalstatus = os.WTERMSIG(status)
1254
self.terminated = True
1255
elif os.WIFSTOPPED(status):
1256
raise ExceptionPexpect('isalive() encountered condition ' +
1257
'where child process is stopped. This is not ' +
1258
'supported. Is some other process attempting ' +
1259
'job control with our child pid?')
1262
def kill(self, sig):
1264
'''This sends the given signal to the child application. In keeping
1265
with UNIX tradition it has a misleading name. It does not necessarily
1266
kill the child unless you send the right signal. '''
1268
# Same as os.kill, but the pid is given for you.
1270
os.kill(self.pid, sig)
1272
def _pattern_type_err(self, pattern):
1273
raise TypeError('got {badtype} ({badobj!r}) as pattern, must be one'
1274
' of: {goodtypes}, pexpect.EOF, pexpect.TIMEOUT'\
1275
.format(badtype=type(pattern),
1277
goodtypes=', '.join([str(ast)\
1278
for ast in self.allowed_string_types])
1282
def compile_pattern_list(self, patterns):
1284
'''This compiles a pattern-string or a list of pattern-strings.
1285
Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
1286
those. Patterns may also be None which results in an empty list (you
1287
might do this if waiting for an EOF or TIMEOUT condition without
1288
expecting any pattern).
1290
This is used by expect() when calling expect_list(). Thus expect() is
1293
cpl = self.compile_pattern_list(pl)
1294
return self.expect_list(cpl, timeout)
1296
If you are using expect() within a loop it may be more
1297
efficient to compile the patterns first and then call expect_list().
1298
This avoid calls in a loop to compile_pattern_list()::
1300
cpl = self.compile_pattern_list(my_pattern)
1301
while some_condition:
1303
i = self.expect_list(clp, timeout)
1307
if patterns is None:
1309
if not isinstance(patterns, list):
1310
patterns = [patterns]
1312
# Allow dot to match \n
1313
compile_flags = re.DOTALL
1315
compile_flags = compile_flags | re.IGNORECASE
1316
compiled_pattern_list = []
1317
for idx, p in enumerate(patterns):
1318
if isinstance(p, self.allowed_string_types):
1319
p = self._coerce_expect_string(p)
1320
compiled_pattern_list.append(re.compile(p, compile_flags))
1322
compiled_pattern_list.append(EOF)
1324
compiled_pattern_list.append(TIMEOUT)
1325
elif isinstance(p, type(re.compile(''))):
1326
compiled_pattern_list.append(p)
1328
self._pattern_type_err(p)
1329
return compiled_pattern_list
1331
def expect(self, pattern, timeout=-1, searchwindowsize=-1):
1333
'''This seeks through the stream until a pattern is matched. The
1334
pattern is overloaded and may take several types. The pattern can be a
1335
StringType, EOF, a compiled re, or a list of any of those types.
1336
Strings will be compiled to re types. This returns the index into the
1337
pattern list. If the pattern was not a list this returns index 0 on a
1338
successful match. This may raise exceptions for EOF or TIMEOUT. To
1339
avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
1340
list. That will cause expect to match an EOF or TIMEOUT condition
1341
instead of raising an exception.
1343
If you pass a list of patterns and more than one matches, the first
1344
match in the stream is chosen. If more than one pattern matches at that
1345
point, the leftmost in the pattern list is chosen. For example::
1347
# the input is 'foobar'
1348
index = p.expect(['bar', 'foo', 'foobar'])
1349
# returns 1('foo') even though 'foobar' is a "better" match
1351
Please note, however, that buffering can affect this behavior, since
1352
input arrives in unpredictable chunks. For example::
1354
# the input is 'foobar'
1355
index = p.expect(['foobar', 'foo'])
1356
# returns 0('foobar') if all input is available at once,
1357
# but returs 1('foo') if parts of the final 'bar' arrive late
1359
After a match is found the instance attributes 'before', 'after' and
1360
'match' will be set. You can see all the data read before the match in
1361
'before'. You can see the data that was matched in 'after'. The
1362
re.MatchObject used in the re match will be in 'match'. If an error
1363
occurred then 'before' will be set to all the data read so far and
1364
'after' and 'match' will be None.
1366
If timeout is -1 then timeout will be set to the self.timeout value.
1368
A list entry may be EOF or TIMEOUT instead of a string. This will
1369
catch these exceptions and return the index of the list entry instead
1370
of raising the exception. The attribute 'after' will be set to the
1371
exception type. The attribute 'match' will be None. This allows you to
1372
write code like this::
1374
index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
1380
do_some_other_thing()
1382
do_something_completely_different()
1384
instead of code like this::
1387
index = p.expect(['good', 'bad'])
1393
do_some_other_thing()
1395
do_something_completely_different()
1397
These two forms are equivalent. It all depends on what you want. You
1398
can also just expect the EOF if you are waiting for all output of a
1399
child to finish. For example::
1401
p = pexpect.spawn('/bin/ls')
1402
p.expect(pexpect.EOF)
1405
If you are trying to optimize for speed then see expect_list().
1408
compiled_pattern_list = self.compile_pattern_list(pattern)
1409
return self.expect_list(compiled_pattern_list,
1410
timeout, searchwindowsize)
1412
def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1):
1414
'''This takes a list of compiled regular expressions and returns the
1415
index into the pattern_list that matched the child output. The list may
1416
also contain EOF or TIMEOUT(which are not compiled regular
1417
expressions). This method is similar to the expect() method except that
1418
expect_list() does not recompile the pattern list on every call. This
1419
may help if you are trying to optimize for speed, otherwise just use
1420
the expect() method. This is called by expect(). If timeout==-1 then
1421
the self.timeout value is used. If searchwindowsize==-1 then the
1422
self.searchwindowsize value is used. '''
1424
return self.expect_loop(searcher_re(pattern_list),
1425
timeout, searchwindowsize)
1427
def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1):
1429
'''This is similar to expect(), but uses plain string matching instead
1430
of compiled regular expressions in 'pattern_list'. The 'pattern_list'
1431
may be a string; a list or other sequence of strings; or TIMEOUT and
1434
This call might be faster than expect() for two reasons: string
1435
searching is faster than RE matching and it is possible to limit the
1436
search to just the end of the input buffer.
1438
This method is also useful when you don't want to have to worry about
1439
escaping regular expression characters that you want to match.'''
1441
if (isinstance(pattern_list, self.allowed_string_types) or
1442
pattern_list in (TIMEOUT, EOF)):
1443
pattern_list = [pattern_list]
1445
def prepare_pattern(pattern):
1446
if pattern in (TIMEOUT, EOF):
1448
if isinstance(pattern, self.allowed_string_types):
1449
return self._coerce_expect_string(pattern)
1450
self._pattern_type_err(pattern)
1453
pattern_list = iter(pattern_list)
1455
self._pattern_type_err(pattern_list)
1456
pattern_list = [prepare_pattern(p) for p in pattern_list]
1457
return self.expect_loop(searcher_string(pattern_list),
1458
timeout, searchwindowsize)
1460
def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1):
1462
'''This is the common loop used inside expect. The 'searcher' should be
1463
an instance of searcher_re or searcher_string, which describes how and
1464
what to search for in the input.
1466
See expect() for other arguments, return value and exceptions. '''
1468
self.searcher = searcher
1471
timeout = self.timeout
1472
if timeout is not None:
1473
end_time = time.time() + timeout
1474
if searchwindowsize == -1:
1475
searchwindowsize = self.searchwindowsize
1478
incoming = self.buffer
1479
freshlen = len(incoming)
1481
# Keep reading until exception or return.
1482
index = searcher.search(incoming, freshlen, searchwindowsize)
1484
self.buffer = incoming[searcher.end:]
1485
self.before = incoming[: searcher.start]
1486
self.after = incoming[searcher.start: searcher.end]
1487
self.match = searcher.match
1488
self.match_index = index
1489
return self.match_index
1490
# No match at this point
1491
if (timeout is not None) and (timeout < 0):
1492
raise TIMEOUT('Timeout exceeded in expect_any().')
1493
# Still have time left, so read more data
1494
c = self.read_nonblocking(self.maxread, timeout)
1497
incoming = incoming + c
1498
if timeout is not None:
1499
timeout = end_time - time.time()
1501
err = sys.exc_info()[1]
1502
self.buffer = self.string_type()
1503
self.before = incoming
1505
index = searcher.eof_index
1508
self.match_index = index
1509
return self.match_index
1512
self.match_index = None
1513
raise EOF(str(err) + '\n' + str(self))
1515
err = sys.exc_info()[1]
1516
self.buffer = incoming
1517
self.before = incoming
1518
self.after = TIMEOUT
1519
index = searcher.timeout_index
1521
self.match = TIMEOUT
1522
self.match_index = index
1523
return self.match_index
1526
self.match_index = None
1527
raise TIMEOUT(str(err) + '\n' + str(self))
1529
self.before = incoming
1532
self.match_index = None
1535
def getwinsize(self):
1537
'''This returns the terminal window size of the child tty. The return
1538
value is a tuple of (rows, cols). '''
1540
TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
1541
s = struct.pack('HHHH', 0, 0, 0, 0)
1542
x = fcntl.ioctl(self.child_fd, TIOCGWINSZ, s)
1543
return struct.unpack('HHHH', x)[0:2]
1545
def setwinsize(self, rows, cols):
1547
'''This sets the terminal window size of the child tty. This will cause
1548
a SIGWINCH signal to be sent to the child. This does not change the
1549
physical window size. It changes the size reported to TTY-aware
1550
applications like vi or curses -- applications that respond to the
1551
SIGWINCH signal. '''
1553
# Check for buggy platforms. Some Python versions on some platforms
1554
# (notably OSF1 Alpha and RedHat 7.1) truncate the value for
1555
# termios.TIOCSWINSZ. It is not clear why this happens.
1556
# These platforms don't seem to handle the signed int very well;
1557
# yet other platforms like OpenBSD have a large negative value for
1558
# TIOCSWINSZ and they don't have a truncate problem.
1559
# Newer versions of Linux have totally different values for TIOCSWINSZ.
1560
# Note that this fix is a hack.
1561
TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
1562
if TIOCSWINSZ == 2148037735:
1563
# Same bits, but with sign.
1564
TIOCSWINSZ = -2146929561
1565
# Note, assume ws_xpixel and ws_ypixel are zero.
1566
s = struct.pack('HHHH', rows, cols, 0, 0)
1567
fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
1569
def interact(self, escape_character=chr(29),
1570
input_filter=None, output_filter=None):
1572
'''This gives control of the child process to the interactive user (the
1573
human at the keyboard). Keystrokes are sent to the child process, and
1574
the stdout and stderr output of the child process is printed. This
1575
simply echos the child stdout and child stderr to the real stdout and
1576
it echos the real stdin to the child stdin. When the user types the
1577
escape_character this method will stop. The default for
1578
escape_character is ^]. This should not be confused with ASCII 27 --
1579
the ESC character. ASCII 29 was chosen for historical merit because
1580
this is the character used by 'telnet' as the escape character. The
1581
escape_character will not be sent to the child process.
1583
You may pass in optional input and output filter functions. These
1584
functions should take a string and return a string. The output_filter
1585
will be passed all the output from the child process. The input_filter
1586
will be passed all the keyboard input from the user. The input_filter
1587
is run BEFORE the check for the escape_character.
1589
Note that if you change the window size of the parent the SIGWINCH
1590
signal will not be passed through to the child. If you want the child
1591
window size to change when the parent's window size changes then do
1592
something like the following example::
1594
import pexpect, struct, fcntl, termios, signal, sys
1595
def sigwinch_passthrough (sig, data):
1596
s = struct.pack("HHHH", 0, 0, 0, 0)
1597
a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
1598
termios.TIOCGWINSZ , s))
1600
p.setwinsize(a[0],a[1])
1601
# Note this 'p' global and used in sigwinch_passthrough.
1602
p = pexpect.spawn('/bin/bash')
1603
signal.signal(signal.SIGWINCH, sigwinch_passthrough)
1608
self.write_to_stdout(self.buffer)
1610
self.buffer = self.string_type()
1611
mode = tty.tcgetattr(self.STDIN_FILENO)
1612
tty.setraw(self.STDIN_FILENO)
1614
escape_character = escape_character.encode('latin-1')
1616
self.__interact_copy(escape_character, input_filter, output_filter)
1618
tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
1620
def __interact_writen(self, fd, data):
1621
'''This is used by the interact() method.
1624
while data != b'' and self.isalive():
1625
n = os.write(fd, data)
1628
def __interact_read(self, fd):
1629
'''This is used by the interact() method.
1632
return os.read(fd, 1000)
1634
def __interact_copy(self, escape_character=None,
1635
input_filter=None, output_filter=None):
1637
'''This is used by the interact() method.
1640
while self.isalive():
1641
r, w, e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
1642
if self.child_fd in r:
1644
data = self.__interact_read(self.child_fd)
1645
except OSError as e:
1646
# The subprocess may have closed before we get to reading it
1647
if e.errno != errno.EIO:
1650
data = output_filter(data)
1651
if self.logfile is not None:
1652
self.logfile.write(data)
1653
self.logfile.flush()
1654
os.write(self.STDOUT_FILENO, data)
1655
if self.STDIN_FILENO in r:
1656
data = self.__interact_read(self.STDIN_FILENO)
1658
data = input_filter(data)
1659
i = data.rfind(escape_character)
1662
self.__interact_writen(self.child_fd, data)
1664
self.__interact_writen(self.child_fd, data)
1666
def __select(self, iwtd, owtd, ewtd, timeout=None):
1668
'''This is a wrapper around select.select() that ignores signals. If
1669
select.select raises a select.error exception and errno is an EINTR
1670
error then it is ignored. Mainly this is used to ignore sigwinch
1671
(terminal resize). '''
1673
# if select() is interrupted by a signal (errno==EINTR) then
1674
# we loop back and enter the select() again.
1675
if timeout is not None:
1676
end_time = time.time() + timeout
1679
return select.select(iwtd, owtd, ewtd, timeout)
1680
except select.error:
1681
err = sys.exc_info()[1]
1682
if err[0] == errno.EINTR:
1683
# if we loop back we have to subtract the
1684
# amount of time we already waited.
1685
if timeout is not None:
1686
timeout = end_time - time.time()
1690
# something else caused the select.error, so
1691
# this actually is an exception.
1694
##############################################################################
1695
# The following methods are no longer supported or allowed.
1697
def setmaxread(self, maxread):
1699
'''This method is no longer supported or allowed. I don't like getters
1700
and setters without a good reason. '''
1702
raise ExceptionPexpect('This method is no longer supported ' +
1703
'or allowed. Just assign a value to the ' +
1704
'maxread member variable.')
1706
def setlog(self, fileobject):
1708
'''This method is no longer supported or allowed.
1711
raise ExceptionPexpect('This method is no longer supported ' +
1712
'or allowed. Just assign a value to the logfile ' +
1715
##############################################################################
1716
# End of spawn class
1717
##############################################################################
1719
class spawnu(spawn):
1720
"""Works like spawn, but accepts and returns unicode strings.
1724
:param encoding: The encoding to use for communications (default: 'utf-8')
1725
:param errors: How to handle encoding/decoding errors; one of 'strict'
1726
(the default), 'ignore', or 'replace', as described
1727
for :meth:`~bytes.decode` and :meth:`~str.encode`.
1731
allowed_string_types = (str, )
1732
_chr = staticmethod(chr)
1733
linesep = os.linesep
1735
string_type = unicode
1736
allowed_string_types = (unicode, )
1737
_chr = staticmethod(unichr)
1738
linesep = os.linesep.decode('ascii')
1739
# This can handle unicode in both Python 2 and 3
1740
write_to_stdout = sys.stdout.write
1742
def __init__(self, *args, **kwargs):
1743
self.encoding = kwargs.pop('encoding', 'utf-8')
1744
self.errors = kwargs.pop('errors', 'strict')
1745
self._decoder = codecs.getincrementaldecoder(self.encoding)(errors=self.errors)
1746
super(spawnu, self).__init__(*args, **kwargs)
1749
def _coerce_expect_string(s):
1753
def _coerce_send_string(s):
1756
def _coerce_read_string(self, s):
1757
return self._decoder.decode(s, final=False)
1760
return os.write(self.child_fd, s.encode(self.encoding, self.errors))
1763
class searcher_string(object):
1765
'''This is a plain string search helper for the spawn.expect_any() method.
1766
This helper class is for speed. For more powerful regex patterns
1767
see the helper class, searcher_re.
1771
eof_index - index of EOF, or -1
1772
timeout_index - index of TIMEOUT, or -1
1774
After a successful match by the search() method the following attributes
1777
start - index into the buffer, first byte of match
1778
end - index into the buffer, first byte after match
1779
match - the matching string itself
1783
def __init__(self, strings):
1785
'''This creates an instance of searcher_string. This argument 'strings'
1786
may be a list; a sequence of strings; or the EOF or TIMEOUT types. '''
1789
self.timeout_index = -1
1791
for n, s in enumerate(strings):
1796
self.timeout_index = n
1798
self._strings.append((n, s))
1802
'''This returns a human-readable string that represents the state of
1805
ss = [(ns[0], ' %d: "%s"' % ns) for ns in self._strings]
1806
ss.append((-1, 'searcher_string:'))
1807
if self.eof_index >= 0:
1808
ss.append((self.eof_index, ' %d: EOF' % self.eof_index))
1809
if self.timeout_index >= 0:
1810
ss.append((self.timeout_index,
1811
' %d: TIMEOUT' % self.timeout_index))
1813
ss = list(zip(*ss))[1]
1814
return '\n'.join(ss)
1816
def search(self, buffer, freshlen, searchwindowsize=None):
1818
'''This searches 'buffer' for the first occurence of one of the search
1819
strings. 'freshlen' must indicate the number of bytes at the end of
1820
'buffer' which have not been searched before. It helps to avoid
1821
searching the same, possibly big, buffer over and over again.
1823
See class spawn for the 'searchwindowsize' argument.
1825
If there is a match this returns the index of that string, and sets
1826
'start', 'end' and 'match'. Otherwise, this returns -1. '''
1830
# 'freshlen' helps a lot here. Further optimizations could
1833
# using something like the Boyer-Moore Fast String Searching
1834
# Algorithm; pre-compiling the search through a list of
1835
# strings into something that can scan the input once to
1836
# search for all N strings; realize that if we search for
1837
# ['bar', 'baz'] and the input is '...foo' we need not bother
1838
# rescanning until we've read three more bytes.
1840
# Sadly, I don't know enough about this interesting topic. /grahn
1842
for index, s in self._strings:
1843
if searchwindowsize is None:
1844
# the match, if any, can only be in the fresh data,
1845
# or at the very end of the old data
1846
offset = -(freshlen + len(s))
1848
# better obey searchwindowsize
1849
offset = -searchwindowsize
1850
n = buffer.find(s, offset)
1851
if n >= 0 and (first_match is None or n < first_match):
1853
best_index, best_match = index, s
1854
if first_match is None:
1856
self.match = best_match
1857
self.start = first_match
1858
self.end = self.start + len(self.match)
1862
class searcher_re(object):
1864
'''This is regular expression string search helper for the
1865
spawn.expect_any() method. This helper class is for powerful
1866
pattern matching. For speed, see the helper class, searcher_string.
1870
eof_index - index of EOF, or -1
1871
timeout_index - index of TIMEOUT, or -1
1873
After a successful match by the search() method the following attributes
1876
start - index into the buffer, first byte of match
1877
end - index into the buffer, first byte after match
1878
match - the re.match object returned by a succesful re.search
1882
def __init__(self, patterns):
1884
'''This creates an instance that searches for 'patterns' Where
1885
'patterns' may be a list or other sequence of compiled regular
1886
expressions, or the EOF or TIMEOUT types.'''
1889
self.timeout_index = -1
1891
for n, s in zip(list(range(len(patterns))), patterns):
1896
self.timeout_index = n
1898
self._searches.append((n, s))
1902
'''This returns a human-readable string that represents the state of
1905
#ss = [(n, ' %d: re.compile("%s")' %
1906
# (n, repr(s.pattern))) for n, s in self._searches]
1908
for n, s in self._searches:
1910
ss.append((n, ' %d: re.compile("%s")' % (n, s.pattern)))
1911
except UnicodeEncodeError:
1912
# for test cases that display __str__ of searches, dont throw
1913
# another exception just because stdout is ascii-only, using
1915
ss.append((n, ' %d: re.compile(%r)' % (n, s.pattern)))
1916
ss.append((-1, 'searcher_re:'))
1917
if self.eof_index >= 0:
1918
ss.append((self.eof_index, ' %d: EOF' % self.eof_index))
1919
if self.timeout_index >= 0:
1920
ss.append((self.timeout_index, ' %d: TIMEOUT' %
1921
self.timeout_index))
1923
ss = list(zip(*ss))[1]
1924
return '\n'.join(ss)
1926
def search(self, buffer, freshlen, searchwindowsize=None):
1928
'''This searches 'buffer' for the first occurence of one of the regular
1929
expressions. 'freshlen' must indicate the number of bytes at the end of
1930
'buffer' which have not been searched before.
1932
See class spawn for the 'searchwindowsize' argument.
1934
If there is a match this returns the index of that string, and sets
1935
'start', 'end' and 'match'. Otherwise, returns -1.'''
1938
# 'freshlen' doesn't help here -- we cannot predict the
1939
# length of a match, and the re module provides no help.
1940
if searchwindowsize is None:
1943
searchstart = max(0, len(buffer) - searchwindowsize)
1944
for index, s in self._searches:
1945
match = s.search(buffer, searchstart)
1949
if first_match is None or n < first_match:
1953
if first_match is None:
1955
self.start = first_match
1956
self.match = the_match
1957
self.end = self.match.end()
1961
def which(filename):
1963
'''This takes a given filename; tries to find it in the environment path;
1964
then checks if it is executable. This returns the full path to the filename
1965
if found and executable. Otherwise this returns None.'''
1967
# Special case where filename contains an explicit path.
1968
if os.path.dirname(filename) != '':
1969
if os.access(filename, os.X_OK):
1971
if 'PATH' not in os.environ or os.environ['PATH'] == '':
1974
p = os.environ['PATH']
1975
pathlist = p.split(os.pathsep)
1976
for path in pathlist:
1977
ff = os.path.join(path, filename)
1978
if os.access(ff, os.X_OK):
1983
def split_command_line(command_line):
1985
'''This splits a command line into a list of arguments. It splits arguments
1986
on spaces, but handles embedded quotes, doublequotes, and escaped
1987
characters. It's impossible to do this with a regular expression, so I
1988
wrote a little state machine to parse the command line. '''
1993
# Constants to name the states we can be in.
1996
state_singlequote = 2
1997
state_doublequote = 3
1998
# The state when consuming whitespace between commands.
1999
state_whitespace = 4
2002
for c in command_line:
2003
if state == state_basic or state == state_whitespace:
2005
# Escape the next character
2008
# Handle single quote
2009
state = state_singlequote
2011
# Handle double quote
2012
state = state_doublequote
2014
# Add arg to arg_list if we aren't in the middle of whitespace.
2015
if state == state_whitespace:
2019
arg_list.append(arg)
2021
state = state_whitespace
2025
elif state == state_esc:
2028
elif state == state_singlequote:
2033
elif state == state_doublequote:
2040
arg_list.append(arg)
2043
# vi:set sr et ts=4 sw=4 ft=python :