~ubuntu-branches/ubuntu/trusty/pexpect/trusty-proposed

« back to all changes in this revision

Viewing changes to pexpect/__init__.py

  • Committer: Package Import Robot
  • Author(s): Andrew Starr-Bochicchio, Thomas Kluyver, Jakub Wilk, Jackson Doak, Andrew Starr-Bochicchio
  • Date: 2013-12-06 20:20:26 UTC
  • mfrom: (1.1.4)
  • Revision ID: package-import@ubuntu.com-20131206202026-9k9oixbv7e8ke30q
Tags: 3.0-1
* Team upload.

[ Thomas Kluyver ]
* New upstream release. Closes: #729518
* Add packaging for Python 3.
* Use pybuild for packaging.

[ Jakub Wilk ]
* Use canonical URIs for Vcs-* fields.

[ Jackson Doak ]
* Create debian/python3-pexpect.docs

[ Andrew Starr-Bochicchio ]
* Remove empty debian/patches dir.
* Move documentation and examples into a new python-pexpect-doc
  package. They are shared between the Python 2 and Python 3 packages,
  so there is no need to install them with both.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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.
 
11
 
 
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().
 
17
 
 
18
For example::
 
19
 
 
20
    pexpect.run('ls -la')
 
21
 
 
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).
 
25
 
 
26
For example::
 
27
 
 
28
    child = pexpect.spawn('scp foo user@example.com:.')
 
29
    child.expect('Password:')
 
30
    child.sendline(mypassword)
 
31
 
 
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.
 
35
 
 
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.
 
43
 
 
44
Pexpect is free, open source, and all that good stuff.
 
45
http://pexpect.sourceforge.net/
 
46
 
 
47
PEXPECT LICENSE
 
48
 
 
49
    This license is approved by the OSI and FSF as GPL-compatible.
 
50
        http://opensource.org/licenses/isc-license.txt
 
51
 
 
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.
 
63
 
 
64
'''
 
65
 
 
66
try:
 
67
    import os
 
68
    import sys
 
69
    import time
 
70
    import select
 
71
    import re
 
72
    import struct
 
73
    import resource
 
74
    import types
 
75
    import pty
 
76
    import tty
 
77
    import termios
 
78
    import fcntl
 
79
    import errno
 
80
    import traceback
 
81
    import signal
 
82
    import codecs
 
83
except ImportError:  # pragma: no cover
 
84
    err = sys.exc_info()[1]
 
85
    raise ImportError(str(err) + '''
 
86
 
 
87
A critical module was not found. Probably this operating system does not
 
88
support it. Pexpect is intended for UNIX-like operating systems.''')
 
89
 
 
90
__version__ = '3.0'
 
91
__revision__ = ''
 
92
__all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnu', 'run', 'runu',
 
93
           'which', 'split_command_line', '__version__', '__revision__']
 
94
 
 
95
PY3 = (sys.version_info[0] >= 3)
 
96
 
 
97
# Exception classes used by this module.
 
98
class ExceptionPexpect(Exception):
 
99
    '''Base class for all exceptions raised by this module.
 
100
    '''
 
101
 
 
102
    def __init__(self, value):
 
103
        self.value = value
 
104
 
 
105
    def __str__(self):
 
106
        return str(self.value)
 
107
 
 
108
    def get_trace(self):
 
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
 
111
        is not included. '''
 
112
 
 
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)
 
117
 
 
118
 
 
119
class EOF(ExceptionPexpect):
 
120
    '''Raised when EOF is read from a child.
 
121
    This usually means the child has exited.'''
 
122
 
 
123
 
 
124
class TIMEOUT(ExceptionPexpect):
 
125
    '''Raised when a read time exceeds the timeout. '''
 
126
 
 
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.
 
132
##    '''
 
133
##class MAXBUFFER(ExceptionPexpect):
 
134
##    '''Raised when a buffer fills before matching an expected pattern.'''
 
135
 
 
136
 
 
137
def run(command, timeout=-1, withexitstatus=False, events=None,
 
138
        extra_args=None, logfile=None, cwd=None, env=None):
 
139
 
 
140
    '''
 
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.
 
144
 
 
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
 
149
    command_output.
 
150
 
 
151
    The run() function can often be used instead of creating a spawn instance.
 
152
    For example, the following code uses spawn::
 
153
 
 
154
        from pexpect import *
 
155
        child = spawn('scp foo user@example.com:.')
 
156
        child.expect('(?i)password')
 
157
        child.sendline(mypassword)
 
158
 
 
159
    The previous code can be replace with the following::
 
160
 
 
161
        from pexpect import *
 
162
        run('scp foo user@example.com:.', events={'(?i)password': mypassword})
 
163
 
 
164
    **Examples**
 
165
 
 
166
    Start the apache daemon on the local machine::
 
167
 
 
168
        from pexpect import *
 
169
        run("/usr/local/apache/bin/apachectl start")
 
170
 
 
171
    Check in a file using SVN::
 
172
 
 
173
        from pexpect import *
 
174
        run("svn ci -m 'automatic commit' my_file.py")
 
175
 
 
176
    Run a command and capture exit status::
 
177
 
 
178
        from pexpect import *
 
179
        (command_output, exitstatus) = run('ls -l /bin', withexitstatus=1)
 
180
 
 
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::
 
183
 
 
184
        run("ssh username@machine.example.com 'ls -l'",
 
185
            events={'(?i)password':'secret\\n'})
 
186
 
 
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::
 
189
 
 
190
        from pexpect import *
 
191
        def print_ticks(d):
 
192
            print d['event_count'],
 
193
        run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
 
194
            events={TIMEOUT:print_ticks}, timeout=5)
 
195
 
 
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.
 
209
    '''
 
210
    return _run(command, timeout=timeout, withexitstatus=withexitstatus,
 
211
                events=events, extra_args=extra_args, logfile=logfile, cwd=cwd,
 
212
                env=env, _spawn=spawn)
 
213
 
 
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.
 
217
 
 
218
    Like :class:`spawnu`, you can pass ``encoding`` and ``errors`` parameters,
 
219
    which will be used for both input and output.
 
220
    """
 
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)
 
224
 
 
225
def _run(command, timeout, withexitstatus, events, extra_args, logfile, cwd,
 
226
         env, _spawn, **kwargs):
 
227
    if timeout == -1:
 
228
        child = _spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env,
 
229
                        **kwargs)
 
230
    else:
 
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())
 
236
    else:
 
237
        # This assumes EOF or TIMEOUT will eventually cause run to terminate.
 
238
        patterns = None
 
239
        responses = None
 
240
    child_result_list = []
 
241
    event_count = 0
 
242
    while True:
 
243
        try:
 
244
            index = child.expect(patterns)
 
245
            if isinstance(child.after, child.allowed_string_types):
 
246
                child_result_list.append(child.before + child.after)
 
247
            else:
 
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())
 
255
                sys.stdout.flush()
 
256
                if isinstance(callback_result, child.allowed_string_types):
 
257
                    child.send(callback_result)
 
258
                elif callback_result:
 
259
                    break
 
260
            else:
 
261
                raise TypeError('The callback must be a string or function.')
 
262
            event_count = event_count + 1
 
263
        except TIMEOUT:
 
264
            child_result_list.append(child.before)
 
265
            break
 
266
        except EOF:
 
267
            child_result_list.append(child.before)
 
268
            break
 
269
    child_result = child.string_type().join(child_result_list)
 
270
    if withexitstatus:
 
271
        child.close()
 
272
        return (child_result, child.exitstatus)
 
273
    else:
 
274
        return child_result
 
275
 
 
276
class spawn(object):
 
277
    '''This is the main class interface for Pexpect. Use this class to start
 
278
    and control child applications. '''
 
279
    string_type = bytes
 
280
    if PY3:
 
281
        allowed_string_types = (bytes, str)
 
282
        @staticmethod
 
283
        def _chr(c):
 
284
            return bytes([c])
 
285
        linesep = os.linesep.encode('ascii')
 
286
        write_to_stdout = sys.stdout.buffer.write
 
287
    else:
 
288
        allowed_string_types = (basestring,)  # analysis:ignore
 
289
        _chr = staticmethod(chr)
 
290
        linesep = os.linesep
 
291
        write_to_stdout = sys.stdout.write
 
292
 
 
293
    encoding = None
 
294
 
 
295
    def __init__(self, command, args=[], timeout=30, maxread=2000,
 
296
        searchwindowsize=None, logfile=None, cwd=None, env=None,
 
297
        ignore_sighup=True):
 
298
 
 
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::
 
301
 
 
302
            child = pexpect.spawn('/usr/bin/ftp')
 
303
            child = pexpect.spawn('/usr/bin/ssh user@example.com')
 
304
            child = pexpect.spawn('ls -latr /tmp')
 
305
 
 
306
        You may also construct it with a list of arguments like so::
 
307
 
 
308
            child = pexpect.spawn('/usr/bin/ftp', [])
 
309
            child = pexpect.spawn('/usr/bin/ssh', ['user@example.com'])
 
310
            child = pexpect.spawn('ls', ['-latr', '/tmp'])
 
311
 
 
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().
 
314
 
 
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::
 
319
 
 
320
            child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')
 
321
            child.expect(pexpect.EOF)
 
322
 
 
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::
 
327
 
 
328
            shell_cmd = 'ls -l | grep LOG > logs.txt'
 
329
            child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
 
330
            child.expect(pexpect.EOF)
 
331
 
 
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.
 
338
 
 
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.
 
348
 
 
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.
 
353
 
 
354
        Example log input and output to a file::
 
355
 
 
356
            child = pexpect.spawn('some_command')
 
357
            fout = file('mylog.txt','w')
 
358
            child.logfile = fout
 
359
 
 
360
        Example log to stdout::
 
361
 
 
362
            child = pexpect.spawn('some_command')
 
363
            child.logfile = sys.stdout
 
364
 
 
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::
 
369
 
 
370
            child = pexpect.spawn('some_command')
 
371
            child.logfile_read = sys.stdout
 
372
 
 
373
        To separately log output sent to the child use logfile_send::
 
374
 
 
375
            self.logfile_send = fout
 
376
 
 
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
 
380
        want to rely on it.
 
381
 
 
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.
 
398
 
 
399
        Note that spawn is clever about finding commands on your path.
 
400
        It uses the same logic that "which" uses to find executables.
 
401
 
 
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. '''
 
411
 
 
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
 
418
 
 
419
        self.searcher = None
 
420
        self.ignorecase = False
 
421
        self.before = None
 
422
        self.after = None
 
423
        self.match = None
 
424
        self.match_index = None
 
425
        self.terminated = True
 
426
        self.exitstatus = None
 
427
        self.signalstatus = None
 
428
        # status returned by os.waitpid
 
429
        self.status = None
 
430
        self.flag_eof = False
 
431
        self.pid = None
 
432
        # the chile filedescriptor is initially closed
 
433
        self.child_fd = -1
 
434
        self.timeout = timeout
 
435
        self.delimiter = EOF
 
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.
 
451
        # Time in seconds.
 
452
        self.delayafterclose = 0.1
 
453
        # Used by terminate() to give kernel time to update process status.
 
454
        # Time in seconds.
 
455
        self.delayafterterminate = 0.1
 
456
        self.softspace = False
 
457
        self.name = '<' + repr(self) + '>'
 
458
        self.closed = True
 
459
        self.cwd = cwd
 
460
        self.env = env
 
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
 
468
        else:
 
469
            self.use_native_pty_fork = True
 
470
 
 
471
        # Support subclasses that do not use command or args.
 
472
        if command is None:
 
473
            self.command = None
 
474
            self.args = None
 
475
            self.name = '<pexpect factory incomplete>'
 
476
        else:
 
477
            self._spawn(command, args)
 
478
 
 
479
    @staticmethod
 
480
    def _coerce_expect_string(s):
 
481
        if not isinstance(s, bytes):
 
482
            return s.encode('ascii')
 
483
        return s
 
484
 
 
485
    @staticmethod
 
486
    def _coerce_send_string(s):
 
487
        if not isinstance(s, bytes):
 
488
            return s.encode('utf-8')
 
489
        return s
 
490
 
 
491
    @staticmethod
 
492
    def _coerce_read_string(s):
 
493
        return s
 
494
 
 
495
    def __del__(self):
 
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. '''
 
501
 
 
502
        if not self.closed:
 
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.
 
506
            try:
 
507
                self.close()
 
508
            # which exception, shouldnt' we catch explicitly .. ?
 
509
            except:
 
510
                pass
 
511
 
 
512
    def __str__(self):
 
513
        '''This returns a human-readable string that represents the state of
 
514
        the object. '''
 
515
 
 
516
        s = []
 
517
        s.append(repr(self))
 
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))
 
543
        return '\n'.join(s)
 
544
 
 
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. '''
 
550
 
 
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.
 
559
 
 
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.')
 
566
 
 
567
        if not isinstance(args, type([])):
 
568
            raise TypeError('The argument, args, must be a list.')
 
569
 
 
570
        if args == []:
 
571
            self.args = split_command_line(command)
 
572
            self.command = self.args[0]
 
573
        else:
 
574
            # Make a shallow copy of the args list.
 
575
            self.args = args[:]
 
576
            self.args.insert(0, command)
 
577
            self.command = command
 
578
 
 
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
 
585
 
 
586
        self.name = '<' + ' '.join(self.args) + '>'
 
587
 
 
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.'
 
590
 
 
591
        if self.use_native_pty_fork:
 
592
            try:
 
593
                self.pid, self.child_fd = pty.fork()
 
594
            except OSError:
 
595
                err = sys.exc_info()[1]
 
596
                raise ExceptionPexpect('pty.fork() failed: ' + str(err))
 
597
        else:
 
598
            # Use internal __fork_pty
 
599
            self.pid, self.child_fd = self.__fork_pty()
 
600
 
 
601
        if self.pid == 0:
 
602
            # Child
 
603
            try:
 
604
                # used by setwinsize()
 
605
                self.child_fd = sys.stdout.fileno()
 
606
                self.setwinsize(24, 80)
 
607
            # which exception, shouldnt' we catch explicitly .. ?
 
608
            except:
 
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.
 
613
                pass
 
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):
 
617
                try:
 
618
                    os.close(i)
 
619
                except OSError:
 
620
                    pass
 
621
 
 
622
            if self.ignore_sighup:
 
623
                signal.signal(signal.SIGHUP, signal.SIG_IGN)
 
624
 
 
625
            if self.cwd is not None:
 
626
                os.chdir(self.cwd)
 
627
            if self.env is None:
 
628
                os.execv(self.command, self.args)
 
629
            else:
 
630
                os.execvpe(self.command, self.args, self.env)
 
631
 
 
632
        # Parent
 
633
        self.terminated = False
 
634
        self.closed = False
 
635
 
 
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.
 
640
 
 
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
 
644
        Spurrier::
 
645
 
 
646
            http://mail.python.org/pipermail/python-dev/2003-May/035281.html
 
647
 
 
648
        '''
 
649
 
 
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().")
 
653
 
 
654
        pid = os.fork()
 
655
        if pid < 0:
 
656
            raise ExceptionPexpect("Failed os.fork().")
 
657
        elif pid == 0:
 
658
            # Child.
 
659
            os.close(parent_fd)
 
660
            self.__pty_make_controlling_tty(child_fd)
 
661
 
 
662
            os.dup2(child_fd, 0)
 
663
            os.dup2(child_fd, 1)
 
664
            os.dup2(child_fd, 2)
 
665
 
 
666
            if child_fd > 2:
 
667
                os.close(child_fd)
 
668
        else:
 
669
            # Parent.
 
670
            os.close(child_fd)
 
671
 
 
672
        return pid, parent_fd
 
673
 
 
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
 
677
        work on Solaris. '''
 
678
 
 
679
        child_name = os.ttyname(tty_fd)
 
680
 
 
681
        # Disconnect from controlling tty. Harmless if not already connected.
 
682
        try:
 
683
            fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
 
684
            if fd >= 0:
 
685
                os.close(fd)
 
686
        # which exception, shouldnt' we catch explicitly .. ?
 
687
        except:
 
688
            # Already disconnected. This happens if running inside cron.
 
689
            pass
 
690
 
 
691
        os.setsid()
 
692
 
 
693
        # Verify we are disconnected from controlling tty
 
694
        # by attempting to open it again.
 
695
        try:
 
696
            fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
 
697
            if fd >= 0:
 
698
                os.close(fd)
 
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 .. ?
 
702
        except:
 
703
            # Good! We are disconnected from a controlling tty.
 
704
            pass
 
705
 
 
706
        # Verify we can open child pty.
 
707
        fd = os.open(child_name, os.O_RDWR)
 
708
        if fd < 0:
 
709
            raise ExceptionPexpect("Could not open child pty, " + child_name)
 
710
        else:
 
711
            os.close(fd)
 
712
 
 
713
        # Verify we now have a controlling tty.
 
714
        fd = os.open("/dev/tty", os.O_WRONLY)
 
715
        if fd < 0:
 
716
            raise ExceptionPexpect("Could not open controlling tty, /dev/tty")
 
717
        else:
 
718
            os.close(fd)
 
719
 
 
720
    def fileno(self):
 
721
        '''This returns the file descriptor of the pty for the child.
 
722
        '''
 
723
        return self.child_fd
 
724
 
 
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
 
730
        and SIGINT). '''
 
731
 
 
732
        if not self.closed:
 
733
            self.flush()
 
734
            os.close(self.child_fd)
 
735
            # Give kernel time to update process status.
 
736
            time.sleep(self.delayafterclose)
 
737
            if self.isalive():
 
738
                if not self.terminate(force):
 
739
                    raise ExceptionPexpect('Could not terminate the child.')
 
740
            self.child_fd = -1
 
741
            self.closed = True
 
742
            #self.pid = None
 
743
 
 
744
    def flush(self):
 
745
        '''This does nothing. It is here to support the interface for a
 
746
        File-like object. '''
 
747
 
 
748
        pass
 
749
 
 
750
    def isatty(self):
 
751
        '''This returns True if the file descriptor is open and connected to a
 
752
        tty(-like) device, else False. '''
 
753
 
 
754
        return os.isatty(self.child_fd)
 
755
 
 
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::
 
764
 
 
765
            p = pexpect.spawn('ssh user@example.com')
 
766
            p.waitnoecho()
 
767
            p.sendline(mypassword)
 
768
 
 
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.
 
771
        '''
 
772
 
 
773
        if timeout == -1:
 
774
            timeout = self.timeout
 
775
        if timeout is not None:
 
776
            end_time = time.time() + timeout
 
777
        while True:
 
778
            if not self.getecho():
 
779
                return True
 
780
            if timeout < 0 and timeout is not None:
 
781
                return False
 
782
            if timeout is not None:
 
783
                timeout = end_time - time.time()
 
784
            time.sleep(0.1)
 
785
 
 
786
    def getecho(self):
 
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(). '''
 
790
 
 
791
        attr = termios.tcgetattr(self.child_fd)
 
792
        if attr[3] & termios.ECHO:
 
793
            return True
 
794
        return False
 
795
 
 
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::
 
801
 
 
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)
 
809
            p.expect(['abcd'])
 
810
            p.expect(['wxyz'])
 
811
 
 
812
        The following WILL NOT WORK because the lines sent before the setecho
 
813
        will be lost::
 
814
 
 
815
            p = pexpect.spawn('cat')
 
816
            p.sendline('1234')
 
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)
 
820
            p.expect(['1234'])
 
821
            p.expect(['1234'])
 
822
            p.expect(['abcd'])
 
823
            p.expect(['wxyz'])
 
824
        '''
 
825
 
 
826
        self.child_fd
 
827
        attr = termios.tcgetattr(self.child_fd)
 
828
        if state:
 
829
            attr[3] = attr[3] | termios.ECHO
 
830
        else:
 
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)
 
836
 
 
837
    def _log(self, s, direction):
 
838
        if self.logfile is not None:
 
839
            self.logfile.write(s)
 
840
            self.logfile.flush()
 
841
        second_log = self.logfile_send if (direction=='send') else self.logfile_read
 
842
        if second_log is not None:
 
843
            second_log.write(s)
 
844
            second_log.flush()
 
845
 
 
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.
 
852
 
 
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.
 
857
 
 
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.
 
863
 
 
864
        This is a wrapper around os.read(). It uses select.select() to
 
865
        implement the timeout. '''
 
866
 
 
867
        if self.closed:
 
868
            raise ValueError('I/O operation on closed file.')
 
869
 
 
870
        if timeout == -1:
 
871
            timeout = self.timeout
 
872
 
 
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)
 
881
            if not r:
 
882
                self.flag_eof = True
 
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():
 
890
                self.flag_eof = True
 
891
                raise EOF('End Of File (EOF). Slow platform.')
 
892
 
 
893
        r, w, e = self.__select([self.child_fd], [], [], timeout)
 
894
 
 
895
        if not r:
 
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.
 
900
                self.flag_eof = True
 
901
                raise EOF('End of File (EOF). Very slow platform.')
 
902
            else:
 
903
                raise TIMEOUT('Timeout exceeded.')
 
904
 
 
905
        if self.child_fd in r:
 
906
            try:
 
907
                s = os.read(self.child_fd, size)
 
908
            except OSError:
 
909
                # Linux does this
 
910
                self.flag_eof = True
 
911
                raise EOF('End Of File (EOF). Exception style platform.')
 
912
            if s == b'':
 
913
                # BSD style
 
914
                self.flag_eof = True
 
915
                raise EOF('End Of File (EOF). Empty string style platform.')
 
916
 
 
917
            s = self._coerce_read_string(s)
 
918
            self._log(s, 'read')
 
919
            return s
 
920
 
 
921
        raise ExceptionPexpect('Reached an unexpected state.')
 
922
 
 
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
 
928
        immediately. '''
 
929
 
 
930
        if size == 0:
 
931
            return self.string_type()
 
932
        if size < 0:
 
933
            # delimiter default is EOF
 
934
            self.expect(self.delimiter)
 
935
            return self.before
 
936
 
 
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])
 
947
        if index == 0:
 
948
            ### FIXME self.before should be ''. Should I assert this?
 
949
            return self.after
 
950
        return self.before
 
951
 
 
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.
 
959
 
 
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. '''
 
963
 
 
964
        if size == 0:
 
965
            return self.string_type()
 
966
        # delimiter default is EOF
 
967
        index = self.expect([b'\r\n', self.delimiter])
 
968
        if index == 0:
 
969
            return self.before + b'\r\n'
 
970
        else:
 
971
            return self.before
 
972
 
 
973
    def __iter__(self):
 
974
        '''This is to support iterators over a file-like object.
 
975
        '''
 
976
        return iter(self.readline, self.string_type())
 
977
 
 
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.'''
 
985
 
 
986
        lines = []
 
987
        while True:
 
988
            line = self.readline()
 
989
            if not line:
 
990
                break
 
991
            lines.append(line)
 
992
        return lines
 
993
 
 
994
    def write(self, s):
 
995
        '''This is similar to send() except that there is no return value.
 
996
        '''
 
997
 
 
998
        self.send(s)
 
999
 
 
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.
 
1004
        '''
 
1005
 
 
1006
        for s in sequence:
 
1007
            self.write(s)
 
1008
 
 
1009
    def send(self, s):
 
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
 
1012
        log. '''
 
1013
 
 
1014
        time.sleep(self.delaybeforesend)
 
1015
 
 
1016
        s = self._coerce_send_string(s)
 
1017
        self._log(s, 'send')
 
1018
 
 
1019
        return self._send(s)
 
1020
 
 
1021
    def _send(self, s):
 
1022
        return os.write(self.child_fd, s)
 
1023
 
 
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. '''
 
1027
 
 
1028
        n = self.send(s)
 
1029
        n = n + self.send(self.linesep)
 
1030
        return n
 
1031
 
 
1032
    def sendcontrol(self, char):
 
1033
 
 
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')::
 
1037
 
 
1038
            child.sendcontrol('g')
 
1039
 
 
1040
        See also, sendintr() and sendeof().
 
1041
        '''
 
1042
 
 
1043
        char = char.lower()
 
1044
        a = ord(char)
 
1045
        if a >= 97 and a <= 122:
 
1046
            a = a - ord('a') + 1
 
1047
            return self.send(self._chr(a))
 
1048
        d = {'@': 0, '`': 0,
 
1049
            '[': 27, '{': 27,
 
1050
            '\\': 28, '|': 28,
 
1051
            ']': 29, '}': 29,
 
1052
            '^': 30, '~': 30,
 
1053
            '_': 31,
 
1054
            '?': 127}
 
1055
        if char not in d:
 
1056
            return 0
 
1057
        return self.send(self._chr(d[char]))
 
1058
 
 
1059
    def sendeof(self):
 
1060
 
 
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. '''
 
1069
 
 
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)
 
1081
        #    else:
 
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])
 
1088
        else:
 
1089
            # platform does not define VEOF so assume CTRL-D
 
1090
            char = 4
 
1091
        self.send(self._chr(char))
 
1092
 
 
1093
    def sendintr(self):
 
1094
 
 
1095
        '''This sends a SIGINT to the child. It does not require
 
1096
        the SIGINT to be the first character on a line. '''
 
1097
 
 
1098
        if hasattr(termios, 'VINTR'):
 
1099
            char = ord(termios.tcgetattr(self.child_fd)[6][termios.VINTR])
 
1100
        else:
 
1101
            # platform does not define VINTR so assume CTRL-C
 
1102
            char = 3
 
1103
        self.send(self._chr(char))
 
1104
 
 
1105
    def eof(self):
 
1106
 
 
1107
        '''This returns True if the EOF exception was ever raised.
 
1108
        '''
 
1109
 
 
1110
        return self.flag_eof
 
1111
 
 
1112
    def terminate(self, force=False):
 
1113
 
 
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. '''
 
1118
 
 
1119
        if not self.isalive():
 
1120
            return True
 
1121
        try:
 
1122
            self.kill(signal.SIGHUP)
 
1123
            time.sleep(self.delayafterterminate)
 
1124
            if not self.isalive():
 
1125
                return True
 
1126
            self.kill(signal.SIGCONT)
 
1127
            time.sleep(self.delayafterterminate)
 
1128
            if not self.isalive():
 
1129
                return True
 
1130
            self.kill(signal.SIGINT)
 
1131
            time.sleep(self.delayafterterminate)
 
1132
            if not self.isalive():
 
1133
                return True
 
1134
            if force:
 
1135
                self.kill(signal.SIGKILL)
 
1136
                time.sleep(self.delayafterterminate)
 
1137
                if not self.isalive():
 
1138
                    return True
 
1139
                else:
 
1140
                    return False
 
1141
            return False
 
1142
        except OSError:
 
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():
 
1149
                return True
 
1150
            else:
 
1151
                return False
 
1152
 
 
1153
    def wait(self):
 
1154
 
 
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. '''
 
1160
 
 
1161
        if self.isalive():
 
1162
            pid, status = os.waitpid(self.pid, 0)
 
1163
        else:
 
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
 
1182
 
 
1183
    def isalive(self):
 
1184
 
 
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. '''
 
1190
 
 
1191
        if self.terminated:
 
1192
            return False
 
1193
 
 
1194
        if self.flag_eof:
 
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.
 
1199
            waitpid_options = 0
 
1200
        else:
 
1201
            waitpid_options = os.WNOHANG
 
1202
 
 
1203
        try:
 
1204
            pid, status = os.waitpid(self.pid, waitpid_options)
 
1205
        except OSError:
 
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() ' +
 
1212
                        'on our process?')
 
1213
            else:
 
1214
                raise err
 
1215
 
 
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.
 
1220
        if pid == 0:
 
1221
            try:
 
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() ' +
 
1230
                            'on our process?')
 
1231
                else:
 
1232
                    raise
 
1233
 
 
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).
 
1239
            if pid == 0:
 
1240
                return True
 
1241
 
 
1242
        if pid == 0:
 
1243
            return True
 
1244
 
 
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?')
 
1260
        return False
 
1261
 
 
1262
    def kill(self, sig):
 
1263
 
 
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. '''
 
1267
 
 
1268
        # Same as os.kill, but the pid is given for you.
 
1269
        if self.isalive():
 
1270
            os.kill(self.pid, sig)
 
1271
 
 
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),
 
1276
                                badobj=pattern,
 
1277
                                goodtypes=', '.join([str(ast)\
 
1278
                                    for ast in self.allowed_string_types])
 
1279
                                )
 
1280
                        )
 
1281
 
 
1282
    def compile_pattern_list(self, patterns):
 
1283
 
 
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).
 
1289
 
 
1290
        This is used by expect() when calling expect_list(). Thus expect() is
 
1291
        nothing more than::
 
1292
 
 
1293
             cpl = self.compile_pattern_list(pl)
 
1294
             return self.expect_list(cpl, timeout)
 
1295
 
 
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()::
 
1299
 
 
1300
             cpl = self.compile_pattern_list(my_pattern)
 
1301
             while some_condition:
 
1302
                ...
 
1303
                i = self.expect_list(clp, timeout)
 
1304
                ...
 
1305
        '''
 
1306
 
 
1307
        if patterns is None:
 
1308
            return []
 
1309
        if not isinstance(patterns, list):
 
1310
            patterns = [patterns]
 
1311
 
 
1312
        # Allow dot to match \n
 
1313
        compile_flags = re.DOTALL
 
1314
        if self.ignorecase:
 
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))
 
1321
            elif p is EOF:
 
1322
                compiled_pattern_list.append(EOF)
 
1323
            elif p is TIMEOUT:
 
1324
                compiled_pattern_list.append(TIMEOUT)
 
1325
            elif isinstance(p, type(re.compile(''))):
 
1326
                compiled_pattern_list.append(p)
 
1327
            else:
 
1328
                self._pattern_type_err(p)
 
1329
        return compiled_pattern_list
 
1330
 
 
1331
    def expect(self, pattern, timeout=-1, searchwindowsize=-1):
 
1332
 
 
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.
 
1342
 
 
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::
 
1346
 
 
1347
            # the input is 'foobar'
 
1348
            index = p.expect(['bar', 'foo', 'foobar'])
 
1349
            # returns 1('foo') even though 'foobar' is a "better" match
 
1350
 
 
1351
        Please note, however, that buffering can affect this behavior, since
 
1352
        input arrives in unpredictable chunks. For example::
 
1353
 
 
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
 
1358
 
 
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.
 
1365
 
 
1366
        If timeout is -1 then timeout will be set to the self.timeout value.
 
1367
 
 
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::
 
1373
 
 
1374
                index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
 
1375
                if index == 0:
 
1376
                    do_something()
 
1377
                elif index == 1:
 
1378
                    do_something_else()
 
1379
                elif index == 2:
 
1380
                    do_some_other_thing()
 
1381
                elif index == 3:
 
1382
                    do_something_completely_different()
 
1383
 
 
1384
        instead of code like this::
 
1385
 
 
1386
                try:
 
1387
                    index = p.expect(['good', 'bad'])
 
1388
                    if index == 0:
 
1389
                        do_something()
 
1390
                    elif index == 1:
 
1391
                        do_something_else()
 
1392
                except EOF:
 
1393
                    do_some_other_thing()
 
1394
                except TIMEOUT:
 
1395
                    do_something_completely_different()
 
1396
 
 
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::
 
1400
 
 
1401
                p = pexpect.spawn('/bin/ls')
 
1402
                p.expect(pexpect.EOF)
 
1403
                print p.before
 
1404
 
 
1405
        If you are trying to optimize for speed then see expect_list().
 
1406
        '''
 
1407
 
 
1408
        compiled_pattern_list = self.compile_pattern_list(pattern)
 
1409
        return self.expect_list(compiled_pattern_list,
 
1410
                timeout, searchwindowsize)
 
1411
 
 
1412
    def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1):
 
1413
 
 
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. '''
 
1423
 
 
1424
        return self.expect_loop(searcher_re(pattern_list),
 
1425
                timeout, searchwindowsize)
 
1426
 
 
1427
    def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1):
 
1428
 
 
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
 
1432
        EOF.
 
1433
 
 
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.
 
1437
 
 
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.'''
 
1440
 
 
1441
        if (isinstance(pattern_list, self.allowed_string_types) or
 
1442
                pattern_list in (TIMEOUT, EOF)):
 
1443
            pattern_list = [pattern_list]
 
1444
 
 
1445
        def prepare_pattern(pattern):
 
1446
            if pattern in (TIMEOUT, EOF):
 
1447
                return pattern
 
1448
            if isinstance(pattern, self.allowed_string_types):
 
1449
                return self._coerce_expect_string(pattern)
 
1450
            self._pattern_type_err(pattern)
 
1451
 
 
1452
        try:
 
1453
            pattern_list = iter(pattern_list)
 
1454
        except TypeError:
 
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)
 
1459
 
 
1460
    def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1):
 
1461
 
 
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.
 
1465
 
 
1466
        See expect() for other arguments, return value and exceptions. '''
 
1467
 
 
1468
        self.searcher = searcher
 
1469
 
 
1470
        if timeout == -1:
 
1471
            timeout = self.timeout
 
1472
        if timeout is not None:
 
1473
            end_time = time.time() + timeout
 
1474
        if searchwindowsize == -1:
 
1475
            searchwindowsize = self.searchwindowsize
 
1476
 
 
1477
        try:
 
1478
            incoming = self.buffer
 
1479
            freshlen = len(incoming)
 
1480
            while True:
 
1481
                # Keep reading until exception or return.
 
1482
                index = searcher.search(incoming, freshlen, searchwindowsize)
 
1483
                if index >= 0:
 
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)
 
1495
                freshlen = len(c)
 
1496
                time.sleep(0.0001)
 
1497
                incoming = incoming + c
 
1498
                if timeout is not None:
 
1499
                    timeout = end_time - time.time()
 
1500
        except EOF:
 
1501
            err = sys.exc_info()[1]
 
1502
            self.buffer = self.string_type()
 
1503
            self.before = incoming
 
1504
            self.after = EOF
 
1505
            index = searcher.eof_index
 
1506
            if index >= 0:
 
1507
                self.match = EOF
 
1508
                self.match_index = index
 
1509
                return self.match_index
 
1510
            else:
 
1511
                self.match = None
 
1512
                self.match_index = None
 
1513
                raise EOF(str(err) + '\n' + str(self))
 
1514
        except TIMEOUT:
 
1515
            err = sys.exc_info()[1]
 
1516
            self.buffer = incoming
 
1517
            self.before = incoming
 
1518
            self.after = TIMEOUT
 
1519
            index = searcher.timeout_index
 
1520
            if index >= 0:
 
1521
                self.match = TIMEOUT
 
1522
                self.match_index = index
 
1523
                return self.match_index
 
1524
            else:
 
1525
                self.match = None
 
1526
                self.match_index = None
 
1527
                raise TIMEOUT(str(err) + '\n' + str(self))
 
1528
        except:
 
1529
            self.before = incoming
 
1530
            self.after = None
 
1531
            self.match = None
 
1532
            self.match_index = None
 
1533
            raise
 
1534
 
 
1535
    def getwinsize(self):
 
1536
 
 
1537
        '''This returns the terminal window size of the child tty. The return
 
1538
        value is a tuple of (rows, cols). '''
 
1539
 
 
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]
 
1544
 
 
1545
    def setwinsize(self, rows, cols):
 
1546
 
 
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. '''
 
1552
 
 
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)
 
1568
 
 
1569
    def interact(self, escape_character=chr(29),
 
1570
            input_filter=None, output_filter=None):
 
1571
 
 
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.
 
1582
 
 
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.
 
1588
 
 
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::
 
1593
 
 
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))
 
1599
                global p
 
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)
 
1604
            p.interact()
 
1605
        '''
 
1606
 
 
1607
        # Flush the buffer.
 
1608
        self.write_to_stdout(self.buffer)
 
1609
        self.stdout.flush()
 
1610
        self.buffer = self.string_type()
 
1611
        mode = tty.tcgetattr(self.STDIN_FILENO)
 
1612
        tty.setraw(self.STDIN_FILENO)
 
1613
        if PY3:
 
1614
            escape_character = escape_character.encode('latin-1')
 
1615
        try:
 
1616
            self.__interact_copy(escape_character, input_filter, output_filter)
 
1617
        finally:
 
1618
            tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
 
1619
 
 
1620
    def __interact_writen(self, fd, data):
 
1621
        '''This is used by the interact() method.
 
1622
        '''
 
1623
 
 
1624
        while data != b'' and self.isalive():
 
1625
            n = os.write(fd, data)
 
1626
            data = data[n:]
 
1627
 
 
1628
    def __interact_read(self, fd):
 
1629
        '''This is used by the interact() method.
 
1630
        '''
 
1631
 
 
1632
        return os.read(fd, 1000)
 
1633
 
 
1634
    def __interact_copy(self, escape_character=None,
 
1635
            input_filter=None, output_filter=None):
 
1636
 
 
1637
        '''This is used by the interact() method.
 
1638
        '''
 
1639
 
 
1640
        while self.isalive():
 
1641
            r, w, e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
 
1642
            if self.child_fd in r:
 
1643
                try:
 
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:
 
1648
                        raise
 
1649
                if output_filter:
 
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)
 
1657
                if input_filter:
 
1658
                    data = input_filter(data)
 
1659
                i = data.rfind(escape_character)
 
1660
                if i != -1:
 
1661
                    data = data[:i]
 
1662
                    self.__interact_writen(self.child_fd, data)
 
1663
                    break
 
1664
                self.__interact_writen(self.child_fd, data)
 
1665
 
 
1666
    def __select(self, iwtd, owtd, ewtd, timeout=None):
 
1667
 
 
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). '''
 
1672
 
 
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
 
1677
        while True:
 
1678
            try:
 
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()
 
1687
                        if timeout < 0:
 
1688
                            return([], [], [])
 
1689
                else:
 
1690
                    # something else caused the select.error, so
 
1691
                    # this actually is an exception.
 
1692
                    raise
 
1693
 
 
1694
##############################################################################
 
1695
# The following methods are no longer supported or allowed.
 
1696
 
 
1697
    def setmaxread(self, maxread):
 
1698
 
 
1699
        '''This method is no longer supported or allowed. I don't like getters
 
1700
        and setters without a good reason. '''
 
1701
 
 
1702
        raise ExceptionPexpect('This method is no longer supported ' +
 
1703
                'or allowed. Just assign a value to the ' +
 
1704
                'maxread member variable.')
 
1705
 
 
1706
    def setlog(self, fileobject):
 
1707
 
 
1708
        '''This method is no longer supported or allowed.
 
1709
        '''
 
1710
 
 
1711
        raise ExceptionPexpect('This method is no longer supported ' +
 
1712
                'or allowed. Just assign a value to the logfile ' +
 
1713
                'member variable.')
 
1714
 
 
1715
##############################################################################
 
1716
# End of spawn class
 
1717
##############################################################################
 
1718
 
 
1719
class spawnu(spawn):
 
1720
    """Works like spawn, but accepts and returns unicode strings.
 
1721
 
 
1722
    Extra parameters:
 
1723
 
 
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`.
 
1728
    """
 
1729
    if PY3:
 
1730
        string_type = str
 
1731
        allowed_string_types = (str, )
 
1732
        _chr = staticmethod(chr)
 
1733
        linesep = os.linesep
 
1734
    else:
 
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
 
1741
 
 
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)
 
1747
 
 
1748
    @staticmethod
 
1749
    def _coerce_expect_string(s):
 
1750
        return s
 
1751
 
 
1752
    @staticmethod
 
1753
    def _coerce_send_string(s):
 
1754
        return s
 
1755
 
 
1756
    def _coerce_read_string(self, s):
 
1757
        return self._decoder.decode(s, final=False)
 
1758
 
 
1759
    def _send(self, s):
 
1760
        return os.write(self.child_fd, s.encode(self.encoding, self.errors))
 
1761
 
 
1762
 
 
1763
class searcher_string(object):
 
1764
 
 
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.
 
1768
 
 
1769
    Attributes:
 
1770
 
 
1771
        eof_index     - index of EOF, or -1
 
1772
        timeout_index - index of TIMEOUT, or -1
 
1773
 
 
1774
    After a successful match by the search() method the following attributes
 
1775
    are available:
 
1776
 
 
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
 
1780
 
 
1781
    '''
 
1782
 
 
1783
    def __init__(self, strings):
 
1784
 
 
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. '''
 
1787
 
 
1788
        self.eof_index = -1
 
1789
        self.timeout_index = -1
 
1790
        self._strings = []
 
1791
        for n, s in enumerate(strings):
 
1792
            if s is EOF:
 
1793
                self.eof_index = n
 
1794
                continue
 
1795
            if s is TIMEOUT:
 
1796
                self.timeout_index = n
 
1797
                continue
 
1798
            self._strings.append((n, s))
 
1799
 
 
1800
    def __str__(self):
 
1801
 
 
1802
        '''This returns a human-readable string that represents the state of
 
1803
        the object.'''
 
1804
 
 
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))
 
1812
        ss.sort()
 
1813
        ss = list(zip(*ss))[1]
 
1814
        return '\n'.join(ss)
 
1815
 
 
1816
    def search(self, buffer, freshlen, searchwindowsize=None):
 
1817
 
 
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.
 
1822
 
 
1823
        See class spawn for the 'searchwindowsize' argument.
 
1824
 
 
1825
        If there is a match this returns the index of that string, and sets
 
1826
        'start', 'end' and 'match'. Otherwise, this returns -1. '''
 
1827
 
 
1828
        first_match = None
 
1829
 
 
1830
        # 'freshlen' helps a lot here. Further optimizations could
 
1831
        # possibly include:
 
1832
        #
 
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.
 
1839
        #
 
1840
        # Sadly, I don't know enough about this interesting topic. /grahn
 
1841
 
 
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))
 
1847
            else:
 
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):
 
1852
                first_match = n
 
1853
                best_index, best_match = index, s
 
1854
        if first_match is None:
 
1855
            return -1
 
1856
        self.match = best_match
 
1857
        self.start = first_match
 
1858
        self.end = self.start + len(self.match)
 
1859
        return best_index
 
1860
 
 
1861
 
 
1862
class searcher_re(object):
 
1863
 
 
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.
 
1867
 
 
1868
    Attributes:
 
1869
 
 
1870
        eof_index     - index of EOF, or -1
 
1871
        timeout_index - index of TIMEOUT, or -1
 
1872
 
 
1873
    After a successful match by the search() method the following attributes
 
1874
    are available:
 
1875
 
 
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
 
1879
 
 
1880
    '''
 
1881
 
 
1882
    def __init__(self, patterns):
 
1883
 
 
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.'''
 
1887
 
 
1888
        self.eof_index = -1
 
1889
        self.timeout_index = -1
 
1890
        self._searches = []
 
1891
        for n, s in zip(list(range(len(patterns))), patterns):
 
1892
            if s is EOF:
 
1893
                self.eof_index = n
 
1894
                continue
 
1895
            if s is TIMEOUT:
 
1896
                self.timeout_index = n
 
1897
                continue
 
1898
            self._searches.append((n, s))
 
1899
 
 
1900
    def __str__(self):
 
1901
 
 
1902
        '''This returns a human-readable string that represents the state of
 
1903
        the object.'''
 
1904
 
 
1905
        #ss = [(n, '    %d: re.compile("%s")' %
 
1906
        #    (n, repr(s.pattern))) for n, s in self._searches]
 
1907
        ss = list()
 
1908
        for n, s in self._searches:
 
1909
            try:
 
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
 
1914
                # repr()
 
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))
 
1922
        ss.sort()
 
1923
        ss = list(zip(*ss))[1]
 
1924
        return '\n'.join(ss)
 
1925
 
 
1926
    def search(self, buffer, freshlen, searchwindowsize=None):
 
1927
 
 
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.
 
1931
 
 
1932
        See class spawn for the 'searchwindowsize' argument.
 
1933
 
 
1934
        If there is a match this returns the index of that string, and sets
 
1935
        'start', 'end' and 'match'. Otherwise, returns -1.'''
 
1936
 
 
1937
        first_match = None
 
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:
 
1941
            searchstart = 0
 
1942
        else:
 
1943
            searchstart = max(0, len(buffer) - searchwindowsize)
 
1944
        for index, s in self._searches:
 
1945
            match = s.search(buffer, searchstart)
 
1946
            if match is None:
 
1947
                continue
 
1948
            n = match.start()
 
1949
            if first_match is None or n < first_match:
 
1950
                first_match = n
 
1951
                the_match = match
 
1952
                best_index = index
 
1953
        if first_match is None:
 
1954
            return -1
 
1955
        self.start = first_match
 
1956
        self.match = the_match
 
1957
        self.end = self.match.end()
 
1958
        return best_index
 
1959
 
 
1960
 
 
1961
def which(filename):
 
1962
 
 
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.'''
 
1966
 
 
1967
    # Special case where filename contains an explicit path.
 
1968
    if os.path.dirname(filename) != '':
 
1969
        if os.access(filename, os.X_OK):
 
1970
            return filename
 
1971
    if 'PATH' not in os.environ or os.environ['PATH'] == '':
 
1972
        p = os.defpath
 
1973
    else:
 
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):
 
1979
            return ff
 
1980
    return None
 
1981
 
 
1982
 
 
1983
def split_command_line(command_line):
 
1984
 
 
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. '''
 
1989
 
 
1990
    arg_list = []
 
1991
    arg = ''
 
1992
 
 
1993
    # Constants to name the states we can be in.
 
1994
    state_basic = 0
 
1995
    state_esc = 1
 
1996
    state_singlequote = 2
 
1997
    state_doublequote = 3
 
1998
    # The state when consuming whitespace between commands.
 
1999
    state_whitespace = 4
 
2000
    state = state_basic
 
2001
 
 
2002
    for c in command_line:
 
2003
        if state == state_basic or state == state_whitespace:
 
2004
            if c == '\\':
 
2005
                # Escape the next character
 
2006
                state = state_esc
 
2007
            elif c == r"'":
 
2008
                # Handle single quote
 
2009
                state = state_singlequote
 
2010
            elif c == r'"':
 
2011
                # Handle double quote
 
2012
                state = state_doublequote
 
2013
            elif c.isspace():
 
2014
                # Add arg to arg_list if we aren't in the middle of whitespace.
 
2015
                if state == state_whitespace:
 
2016
                    # Do nothing.
 
2017
                    None
 
2018
                else:
 
2019
                    arg_list.append(arg)
 
2020
                    arg = ''
 
2021
                    state = state_whitespace
 
2022
            else:
 
2023
                arg = arg + c
 
2024
                state = state_basic
 
2025
        elif state == state_esc:
 
2026
            arg = arg + c
 
2027
            state = state_basic
 
2028
        elif state == state_singlequote:
 
2029
            if c == r"'":
 
2030
                state = state_basic
 
2031
            else:
 
2032
                arg = arg + c
 
2033
        elif state == state_doublequote:
 
2034
            if c == r'"':
 
2035
                state = state_basic
 
2036
            else:
 
2037
                arg = arg + c
 
2038
 
 
2039
    if arg != '':
 
2040
        arg_list.append(arg)
 
2041
    return arg_list
 
2042
 
 
2043
# vi:set sr et ts=4 sw=4 ft=python :