[sanitizer] Improve FreeBSD ASLR detection
[llvm-project.git] / lldb / third_party / Python / module / pexpect-4.6 / pexpect / pty_spawn.py
blob6b9ad3f63f7cd11b2ce619e84fd958114765c44f
1 import os
2 import sys
3 import time
4 import pty
5 import tty
6 import errno
7 import signal
8 from contextlib import contextmanager
10 import ptyprocess
11 from ptyprocess.ptyprocess import use_native_pty_fork
13 from .exceptions import ExceptionPexpect, EOF, TIMEOUT
14 from .spawnbase import SpawnBase
15 from .utils import (
16 which, split_command_line, select_ignore_interrupts, poll_ignore_interrupts
19 @contextmanager
20 def _wrap_ptyprocess_err():
21 """Turn ptyprocess errors into our own ExceptionPexpect errors"""
22 try:
23 yield
24 except ptyprocess.PtyProcessError as e:
25 raise ExceptionPexpect(*e.args)
27 PY3 = (sys.version_info[0] >= 3)
29 class spawn(SpawnBase):
30 '''This is the main class interface for Pexpect. Use this class to start
31 and control child applications. '''
33 # This is purely informational now - changing it has no effect
34 use_native_pty_fork = use_native_pty_fork
36 def __init__(self, command, args=[], timeout=30, maxread=2000,
37 searchwindowsize=None, logfile=None, cwd=None, env=None,
38 ignore_sighup=False, echo=True, preexec_fn=None,
39 encoding=None, codec_errors='strict', dimensions=None,
40 use_poll=False):
41 '''This is the constructor. The command parameter may be a string that
42 includes a command and any arguments to the command. For example::
44 child = pexpect.spawn('/usr/bin/ftp')
45 child = pexpect.spawn('/usr/bin/ssh user@example.com')
46 child = pexpect.spawn('ls -latr /tmp')
48 You may also construct it with a list of arguments like so::
50 child = pexpect.spawn('/usr/bin/ftp', [])
51 child = pexpect.spawn('/usr/bin/ssh', ['user@example.com'])
52 child = pexpect.spawn('ls', ['-latr', '/tmp'])
54 After this the child application will be created and will be ready to
55 talk to. For normal use, see expect() and send() and sendline().
57 Remember that Pexpect does NOT interpret shell meta characters such as
58 redirect, pipe, or wild cards (``>``, ``|``, or ``*``). This is a
59 common mistake. If you want to run a command and pipe it through
60 another command then you must also start a shell. For example::
62 child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')
63 child.expect(pexpect.EOF)
65 The second form of spawn (where you pass a list of arguments) is useful
66 in situations where you wish to spawn a command and pass it its own
67 argument list. This can make syntax more clear. For example, the
68 following is equivalent to the previous example::
70 shell_cmd = 'ls -l | grep LOG > logs.txt'
71 child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
72 child.expect(pexpect.EOF)
74 The maxread attribute sets the read buffer size. This is maximum number
75 of bytes that Pexpect will try to read from a TTY at one time. Setting
76 the maxread size to 1 will turn off buffering. Setting the maxread
77 value higher may help performance in cases where large amounts of
78 output are read back from the child. This feature is useful in
79 conjunction with searchwindowsize.
81 When the keyword argument *searchwindowsize* is None (default), the
82 full buffer is searched at each iteration of receiving incoming data.
83 The default number of bytes scanned at each iteration is very large
84 and may be reduced to collaterally reduce search cost. After
85 :meth:`~.expect` returns, the full buffer attribute remains up to
86 size *maxread* irrespective of *searchwindowsize* value.
88 When the keyword argument ``timeout`` is specified as a number,
89 (default: *30*), then :class:`TIMEOUT` will be raised after the value
90 specified has elapsed, in seconds, for any of the :meth:`~.expect`
91 family of method calls. When None, TIMEOUT will not be raised, and
92 :meth:`~.expect` may block indefinitely until match.
95 The logfile member turns on or off logging. All input and output will
96 be copied to the given file object. Set logfile to None to stop
97 logging. This is the default. Set logfile to sys.stdout to echo
98 everything to standard output. The logfile is flushed after each write.
100 Example log input and output to a file::
102 child = pexpect.spawn('some_command')
103 fout = open('mylog.txt','wb')
104 child.logfile = fout
106 Example log to stdout::
108 # In Python 2:
109 child = pexpect.spawn('some_command')
110 child.logfile = sys.stdout
112 # In Python 3, we'll use the ``encoding`` argument to decode data
113 # from the subprocess and handle it as unicode:
114 child = pexpect.spawn('some_command', encoding='utf-8')
115 child.logfile = sys.stdout
117 The logfile_read and logfile_send members can be used to separately log
118 the input from the child and output sent to the child. Sometimes you
119 don't want to see everything you write to the child. You only want to
120 log what the child sends back. For example::
122 child = pexpect.spawn('some_command')
123 child.logfile_read = sys.stdout
125 You will need to pass an encoding to spawn in the above code if you are
126 using Python 3.
128 To separately log output sent to the child use logfile_send::
130 child.logfile_send = fout
132 If ``ignore_sighup`` is True, the child process will ignore SIGHUP
133 signals. The default is False from Pexpect 4.0, meaning that SIGHUP
134 will be handled normally by the child.
136 The delaybeforesend helps overcome a weird behavior that many users
137 were experiencing. The typical problem was that a user would expect() a
138 "Password:" prompt and then immediately call sendline() to send the
139 password. The user would then see that their password was echoed back
140 to them. Passwords don't normally echo. The problem is caused by the
141 fact that most applications print out the "Password" prompt and then
142 turn off stdin echo, but if you send your password before the
143 application turned off echo, then you get your password echoed.
144 Normally this wouldn't be a problem when interacting with a human at a
145 real keyboard. If you introduce a slight delay just before writing then
146 this seems to clear up the problem. This was such a common problem for
147 many users that I decided that the default pexpect behavior should be
148 to sleep just before writing to the child application. 1/20th of a
149 second (50 ms) seems to be enough to clear up the problem. You can set
150 delaybeforesend to None to return to the old behavior.
152 Note that spawn is clever about finding commands on your path.
153 It uses the same logic that "which" uses to find executables.
155 If you wish to get the exit status of the child you must call the
156 close() method. The exit or signal status of the child will be stored
157 in self.exitstatus or self.signalstatus. If the child exited normally
158 then exitstatus will store the exit return code and signalstatus will
159 be None. If the child was terminated abnormally with a signal then
160 signalstatus will store the signal value and exitstatus will be None::
162 child = pexpect.spawn('some_command')
163 child.close()
164 print(child.exitstatus, child.signalstatus)
166 If you need more detail you can also read the self.status member which
167 stores the status returned by os.waitpid. You can interpret this using
168 os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.
170 The echo attribute may be set to False to disable echoing of input.
171 As a pseudo-terminal, all input echoed by the "keyboard" (send()
172 or sendline()) will be repeated to output. For many cases, it is
173 not desirable to have echo enabled, and it may be later disabled
174 using setecho(False) followed by waitnoecho(). However, for some
175 platforms such as Solaris, this is not possible, and should be
176 disabled immediately on spawn.
178 If preexec_fn is given, it will be called in the child process before
179 launching the given command. This is useful to e.g. reset inherited
180 signal handlers.
182 The dimensions attribute specifies the size of the pseudo-terminal as
183 seen by the subprocess, and is specified as a two-entry tuple (rows,
184 columns). If this is unspecified, the defaults in ptyprocess will apply.
186 The use_poll attribute enables using select.poll() over select.select()
187 for socket handling. This is handy if your system could have > 1024 fds
189 super(spawn, self).__init__(timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize,
190 logfile=logfile, encoding=encoding, codec_errors=codec_errors)
191 self.STDIN_FILENO = pty.STDIN_FILENO
192 self.STDOUT_FILENO = pty.STDOUT_FILENO
193 self.STDERR_FILENO = pty.STDERR_FILENO
194 self.cwd = cwd
195 self.env = env
196 self.echo = echo
197 self.ignore_sighup = ignore_sighup
198 self.__irix_hack = sys.platform.lower().startswith('irix')
199 if command is None:
200 self.command = None
201 self.args = None
202 self.name = '<pexpect factory incomplete>'
203 else:
204 self._spawn(command, args, preexec_fn, dimensions)
205 self.use_poll = use_poll
207 def __str__(self):
208 '''This returns a human-readable string that represents the state of
209 the object. '''
211 s = []
212 s.append(repr(self))
213 s.append('command: ' + str(self.command))
214 s.append('args: %r' % (self.args,))
215 s.append('buffer (last 100 chars): %r' % self.buffer[-100:])
216 s.append('before (last 100 chars): %r' % self.before[-100:] if self.before else '')
217 s.append('after: %r' % (self.after,))
218 s.append('match: %r' % (self.match,))
219 s.append('match_index: ' + str(self.match_index))
220 s.append('exitstatus: ' + str(self.exitstatus))
221 if hasattr(self, 'ptyproc'):
222 s.append('flag_eof: ' + str(self.flag_eof))
223 s.append('pid: ' + str(self.pid))
224 s.append('child_fd: ' + str(self.child_fd))
225 s.append('closed: ' + str(self.closed))
226 s.append('timeout: ' + str(self.timeout))
227 s.append('delimiter: ' + str(self.delimiter))
228 s.append('logfile: ' + str(self.logfile))
229 s.append('logfile_read: ' + str(self.logfile_read))
230 s.append('logfile_send: ' + str(self.logfile_send))
231 s.append('maxread: ' + str(self.maxread))
232 s.append('ignorecase: ' + str(self.ignorecase))
233 s.append('searchwindowsize: ' + str(self.searchwindowsize))
234 s.append('delaybeforesend: ' + str(self.delaybeforesend))
235 s.append('delayafterclose: ' + str(self.delayafterclose))
236 s.append('delayafterterminate: ' + str(self.delayafterterminate))
237 return '\n'.join(s)
239 def _spawn(self, command, args=[], preexec_fn=None, dimensions=None):
240 '''This starts the given command in a child process. This does all the
241 fork/exec type of stuff for a pty. This is called by __init__. If args
242 is empty then command will be parsed (split on spaces) and args will be
243 set to parsed arguments. '''
245 # The pid and child_fd of this object get set by this method.
246 # Note that it is difficult for this method to fail.
247 # You cannot detect if the child process cannot start.
248 # So the only way you can tell if the child process started
249 # or not is to try to read from the file descriptor. If you get
250 # EOF immediately then it means that the child is already dead.
251 # That may not necessarily be bad because you may have spawned a child
252 # that performs some task; creates no stdout output; and then dies.
254 # If command is an int type then it may represent a file descriptor.
255 if isinstance(command, type(0)):
256 raise ExceptionPexpect('Command is an int type. ' +
257 'If this is a file descriptor then maybe you want to ' +
258 'use fdpexpect.fdspawn which takes an existing ' +
259 'file descriptor instead of a command string.')
261 if not isinstance(args, type([])):
262 raise TypeError('The argument, args, must be a list.')
264 if args == []:
265 self.args = split_command_line(command)
266 self.command = self.args[0]
267 else:
268 # Make a shallow copy of the args list.
269 self.args = args[:]
270 self.args.insert(0, command)
271 self.command = command
273 command_with_path = which(self.command, env=self.env)
274 if command_with_path is None:
275 raise ExceptionPexpect('The command was not found or was not ' +
276 'executable: %s.' % self.command)
277 self.command = command_with_path
278 self.args[0] = self.command
280 self.name = '<' + ' '.join(self.args) + '>'
282 assert self.pid is None, 'The pid member must be None.'
283 assert self.command is not None, 'The command member must not be None.'
285 kwargs = {'echo': self.echo, 'preexec_fn': preexec_fn}
286 if self.ignore_sighup:
287 def preexec_wrapper():
288 "Set SIGHUP to be ignored, then call the real preexec_fn"
289 signal.signal(signal.SIGHUP, signal.SIG_IGN)
290 if preexec_fn is not None:
291 preexec_fn()
292 kwargs['preexec_fn'] = preexec_wrapper
294 if dimensions is not None:
295 kwargs['dimensions'] = dimensions
297 if self.encoding is not None:
298 # Encode command line using the specified encoding
299 self.args = [a if isinstance(a, bytes) else a.encode(self.encoding)
300 for a in self.args]
302 self.ptyproc = self._spawnpty(self.args, env=self.env,
303 cwd=self.cwd, **kwargs)
305 self.pid = self.ptyproc.pid
306 self.child_fd = self.ptyproc.fd
309 self.terminated = False
310 self.closed = False
312 def _spawnpty(self, args, **kwargs):
313 '''Spawn a pty and return an instance of PtyProcess.'''
314 return ptyprocess.PtyProcess.spawn(args, **kwargs)
316 def close(self, force=True):
317 '''This closes the connection with the child application. Note that
318 calling close() more than once is valid. This emulates standard Python
319 behavior with files. Set force to True if you want to make sure that
320 the child is terminated (SIGKILL is sent if the child ignores SIGHUP
321 and SIGINT). '''
323 self.flush()
324 with _wrap_ptyprocess_err():
325 # PtyProcessError may be raised if it is not possible to terminate
326 # the child.
327 self.ptyproc.close(force=force)
328 self.isalive() # Update exit status from ptyproc
329 self.child_fd = -1
330 self.closed = True
332 def isatty(self):
333 '''This returns True if the file descriptor is open and connected to a
334 tty(-like) device, else False.
336 On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
337 the child pty may not appear as a terminal device. This means
338 methods such as setecho(), setwinsize(), getwinsize() may raise an
339 IOError. '''
341 return os.isatty(self.child_fd)
343 def waitnoecho(self, timeout=-1):
344 '''This waits until the terminal ECHO flag is set False. This returns
345 True if the echo mode is off. This returns False if the ECHO flag was
346 not set False before the timeout. This can be used to detect when the
347 child is waiting for a password. Usually a child application will turn
348 off echo mode when it is waiting for the user to enter a password. For
349 example, instead of expecting the "password:" prompt you can wait for
350 the child to set ECHO off::
352 p = pexpect.spawn('ssh user@example.com')
353 p.waitnoecho()
354 p.sendline(mypassword)
356 If timeout==-1 then this method will use the value in self.timeout.
357 If timeout==None then this method to block until ECHO flag is False.
360 if timeout == -1:
361 timeout = self.timeout
362 if timeout is not None:
363 end_time = time.time() + timeout
364 while True:
365 if not self.getecho():
366 return True
367 if timeout < 0 and timeout is not None:
368 return False
369 if timeout is not None:
370 timeout = end_time - time.time()
371 time.sleep(0.1)
373 def getecho(self):
374 '''This returns the terminal echo mode. This returns True if echo is
375 on or False if echo is off. Child applications that are expecting you
376 to enter a password often set ECHO False. See waitnoecho().
378 Not supported on platforms where ``isatty()`` returns False. '''
379 return self.ptyproc.getecho()
381 def setecho(self, state):
382 '''This sets the terminal echo mode on or off. Note that anything the
383 child sent before the echo will be lost, so you should be sure that
384 your input buffer is empty before you call setecho(). For example, the
385 following will work as expected::
387 p = pexpect.spawn('cat') # Echo is on by default.
388 p.sendline('1234') # We expect see this twice from the child...
389 p.expect(['1234']) # ... once from the tty echo...
390 p.expect(['1234']) # ... and again from cat itself.
391 p.setecho(False) # Turn off tty echo
392 p.sendline('abcd') # We will set this only once (echoed by cat).
393 p.sendline('wxyz') # We will set this only once (echoed by cat)
394 p.expect(['abcd'])
395 p.expect(['wxyz'])
397 The following WILL NOT WORK because the lines sent before the setecho
398 will be lost::
400 p = pexpect.spawn('cat')
401 p.sendline('1234')
402 p.setecho(False) # Turn off tty echo
403 p.sendline('abcd') # We will set this only once (echoed by cat).
404 p.sendline('wxyz') # We will set this only once (echoed by cat)
405 p.expect(['1234'])
406 p.expect(['1234'])
407 p.expect(['abcd'])
408 p.expect(['wxyz'])
411 Not supported on platforms where ``isatty()`` returns False.
413 return self.ptyproc.setecho(state)
415 def read_nonblocking(self, size=1, timeout=-1):
416 '''This reads at most size characters from the child application. It
417 includes a timeout. If the read does not complete within the timeout
418 period then a TIMEOUT exception is raised. If the end of file is read
419 then an EOF exception will be raised. If a logfile is specified, a
420 copy is written to that log.
422 If timeout is None then the read may block indefinitely.
423 If timeout is -1 then the self.timeout value is used. If timeout is 0
424 then the child is polled and if there is no data immediately ready
425 then this will raise a TIMEOUT exception.
427 The timeout refers only to the amount of time to read at least one
428 character. This is not affected by the 'size' parameter, so if you call
429 read_nonblocking(size=100, timeout=30) and only one character is
430 available right away then one character will be returned immediately.
431 It will not wait for 30 seconds for another 99 characters to come in.
433 This is a wrapper around os.read(). It uses select.select() to
434 implement the timeout. '''
436 if self.closed:
437 raise ValueError('I/O operation on closed file.')
439 if timeout == -1:
440 timeout = self.timeout
442 # Note that some systems such as Solaris do not give an EOF when
443 # the child dies. In fact, you can still try to read
444 # from the child_fd -- it will block forever or until TIMEOUT.
445 # For this case, I test isalive() before doing any reading.
446 # If isalive() is false, then I pretend that this is the same as EOF.
447 if not self.isalive():
448 # timeout of 0 means "poll"
449 if self.use_poll:
450 r = poll_ignore_interrupts([self.child_fd], timeout)
451 else:
452 r, w, e = select_ignore_interrupts([self.child_fd], [], [], 0)
453 if not r:
454 self.flag_eof = True
455 raise EOF('End Of File (EOF). Braindead platform.')
456 elif self.__irix_hack:
457 # Irix takes a long time before it realizes a child was terminated.
458 # FIXME So does this mean Irix systems are forced to always have
459 # FIXME a 2 second delay when calling read_nonblocking? That sucks.
460 if self.use_poll:
461 r = poll_ignore_interrupts([self.child_fd], timeout)
462 else:
463 r, w, e = select_ignore_interrupts([self.child_fd], [], [], 2)
464 if not r and not self.isalive():
465 self.flag_eof = True
466 raise EOF('End Of File (EOF). Slow platform.')
467 if self.use_poll:
468 r = poll_ignore_interrupts([self.child_fd], timeout)
469 else:
470 r, w, e = select_ignore_interrupts(
471 [self.child_fd], [], [], timeout
474 if not r:
475 if not self.isalive():
476 # Some platforms, such as Irix, will claim that their
477 # processes are alive; timeout on the select; and
478 # then finally admit that they are not alive.
479 self.flag_eof = True
480 raise EOF('End of File (EOF). Very slow platform.')
481 else:
482 raise TIMEOUT('Timeout exceeded.')
484 if self.child_fd in r:
485 return super(spawn, self).read_nonblocking(size)
487 raise ExceptionPexpect('Reached an unexpected state.') # pragma: no cover
489 def write(self, s):
490 '''This is similar to send() except that there is no return value.
493 self.send(s)
495 def writelines(self, sequence):
496 '''This calls write() for each element in the sequence. The sequence
497 can be any iterable object producing strings, typically a list of
498 strings. This does not add line separators. There is no return value.
501 for s in sequence:
502 self.write(s)
504 def send(self, s):
505 '''Sends string ``s`` to the child process, returning the number of
506 bytes written. If a logfile is specified, a copy is written to that
507 log.
509 The default terminal input mode is canonical processing unless set
510 otherwise by the child process. This allows backspace and other line
511 processing to be performed prior to transmitting to the receiving
512 program. As this is buffered, there is a limited size of such buffer.
514 On Linux systems, this is 4096 (defined by N_TTY_BUF_SIZE). All
515 other systems honor the POSIX.1 definition PC_MAX_CANON -- 1024
516 on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.
518 This value may be discovered using fpathconf(3)::
520 >>> from os import fpathconf
521 >>> print(fpathconf(0, 'PC_MAX_CANON'))
524 On such a system, only 256 bytes may be received per line. Any
525 subsequent bytes received will be discarded. BEL (``'\a'``) is then
526 sent to output if IMAXBEL (termios.h) is set by the tty driver.
527 This is usually enabled by default. Linux does not honor this as
528 an option -- it behaves as though it is always set on.
530 Canonical input processing may be disabled altogether by executing
531 a shell, then stty(1), before executing the final program::
533 >>> bash = pexpect.spawn('/bin/bash', echo=False)
534 >>> bash.sendline('stty -icanon')
535 >>> bash.sendline('base64')
536 >>> bash.sendline('x' * 5000)
539 if self.delaybeforesend is not None:
540 time.sleep(self.delaybeforesend)
542 s = self._coerce_send_string(s)
543 self._log(s, 'send')
545 b = self._encoder.encode(s, final=False)
546 return os.write(self.child_fd, b)
548 def sendline(self, s=''):
549 '''Wraps send(), sending string ``s`` to child process, with
550 ``os.linesep`` automatically appended. Returns number of bytes
551 written. Only a limited number of bytes may be sent for each
552 line in the default terminal mode, see docstring of :meth:`send`.
554 s = self._coerce_send_string(s)
555 return self.send(s + self.linesep)
557 def _log_control(self, s):
558 """Write control characters to the appropriate log files"""
559 if self.encoding is not None:
560 s = s.decode(self.encoding, 'replace')
561 self._log(s, 'send')
563 def sendcontrol(self, char):
564 '''Helper method that wraps send() with mnemonic access for sending control
565 character to the child (such as Ctrl-C or Ctrl-D). For example, to send
566 Ctrl-G (ASCII 7, bell, '\a')::
568 child.sendcontrol('g')
570 See also, sendintr() and sendeof().
572 n, byte = self.ptyproc.sendcontrol(char)
573 self._log_control(byte)
574 return n
576 def sendeof(self):
577 '''This sends an EOF to the child. This sends a character which causes
578 the pending parent output buffer to be sent to the waiting child
579 program without waiting for end-of-line. If it is the first character
580 of the line, the read() in the user program returns 0, which signifies
581 end-of-file. This means to work as expected a sendeof() has to be
582 called at the beginning of a line. This method does not send a newline.
583 It is the responsibility of the caller to ensure the eof is sent at the
584 beginning of a line. '''
586 n, byte = self.ptyproc.sendeof()
587 self._log_control(byte)
589 def sendintr(self):
590 '''This sends a SIGINT to the child. It does not require
591 the SIGINT to be the first character on a line. '''
593 n, byte = self.ptyproc.sendintr()
594 self._log_control(byte)
596 @property
597 def flag_eof(self):
598 return self.ptyproc.flag_eof
600 @flag_eof.setter
601 def flag_eof(self, value):
602 self.ptyproc.flag_eof = value
604 def eof(self):
605 '''This returns True if the EOF exception was ever raised.
607 return self.flag_eof
609 def terminate(self, force=False):
610 '''This forces a child process to terminate. It starts nicely with
611 SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
612 returns True if the child was terminated. This returns False if the
613 child could not be terminated. '''
615 if not self.isalive():
616 return True
617 try:
618 self.kill(signal.SIGHUP)
619 time.sleep(self.delayafterterminate)
620 if not self.isalive():
621 return True
622 self.kill(signal.SIGCONT)
623 time.sleep(self.delayafterterminate)
624 if not self.isalive():
625 return True
626 self.kill(signal.SIGINT)
627 time.sleep(self.delayafterterminate)
628 if not self.isalive():
629 return True
630 if force:
631 self.kill(signal.SIGKILL)
632 time.sleep(self.delayafterterminate)
633 if not self.isalive():
634 return True
635 else:
636 return False
637 return False
638 except OSError:
639 # I think there are kernel timing issues that sometimes cause
640 # this to happen. I think isalive() reports True, but the
641 # process is dead to the kernel.
642 # Make one last attempt to see if the kernel is up to date.
643 time.sleep(self.delayafterterminate * 10)
644 if not self.isalive():
645 return True
646 else:
647 return False
649 def wait(self):
650 '''This waits until the child exits. This is a blocking call. This will
651 not read any data from the child, so this will block forever if the
652 child has unread output and has terminated. In other words, the child
653 may have printed output then called exit(), but, the child is
654 technically still alive until its output is read by the parent.
656 This method is non-blocking if :meth:`wait` has already been called
657 previously or :meth:`isalive` method returns False. It simply returns
658 the previously determined exit status.
661 ptyproc = self.ptyproc
662 with _wrap_ptyprocess_err():
663 # exception may occur if "Is some other process attempting
664 # "job control with our child pid?"
665 exitstatus = ptyproc.wait()
666 self.status = ptyproc.status
667 self.exitstatus = ptyproc.exitstatus
668 self.signalstatus = ptyproc.signalstatus
669 self.terminated = True
671 return exitstatus
673 def isalive(self):
674 '''This tests if the child process is running or not. This is
675 non-blocking. If the child was terminated then this will read the
676 exitstatus or signalstatus of the child. This returns True if the child
677 process appears to be running or False if not. It can take literally
678 SECONDS for Solaris to return the right status. '''
680 ptyproc = self.ptyproc
681 with _wrap_ptyprocess_err():
682 alive = ptyproc.isalive()
684 if not alive:
685 self.status = ptyproc.status
686 self.exitstatus = ptyproc.exitstatus
687 self.signalstatus = ptyproc.signalstatus
688 self.terminated = True
690 return alive
692 def kill(self, sig):
694 '''This sends the given signal to the child application. In keeping
695 with UNIX tradition it has a misleading name. It does not necessarily
696 kill the child unless you send the right signal. '''
698 # Same as os.kill, but the pid is given for you.
699 if self.isalive():
700 os.kill(self.pid, sig)
702 def getwinsize(self):
703 '''This returns the terminal window size of the child tty. The return
704 value is a tuple of (rows, cols). '''
705 return self.ptyproc.getwinsize()
707 def setwinsize(self, rows, cols):
708 '''This sets the terminal window size of the child tty. This will cause
709 a SIGWINCH signal to be sent to the child. This does not change the
710 physical window size. It changes the size reported to TTY-aware
711 applications like vi or curses -- applications that respond to the
712 SIGWINCH signal. '''
713 return self.ptyproc.setwinsize(rows, cols)
716 def interact(self, escape_character=chr(29),
717 input_filter=None, output_filter=None):
719 '''This gives control of the child process to the interactive user (the
720 human at the keyboard). Keystrokes are sent to the child process, and
721 the stdout and stderr output of the child process is printed. This
722 simply echos the child stdout and child stderr to the real stdout and
723 it echos the real stdin to the child stdin. When the user types the
724 escape_character this method will return None. The escape_character
725 will not be transmitted. The default for escape_character is
726 entered as ``Ctrl - ]``, the very same as BSD telnet. To prevent
727 escaping, escape_character may be set to None.
729 If a logfile is specified, then the data sent and received from the
730 child process in interact mode is duplicated to the given log.
732 You may pass in optional input and output filter functions. These
733 functions should take a string and return a string. The output_filter
734 will be passed all the output from the child process. The input_filter
735 will be passed all the keyboard input from the user. The input_filter
736 is run BEFORE the check for the escape_character.
738 Note that if you change the window size of the parent the SIGWINCH
739 signal will not be passed through to the child. If you want the child
740 window size to change when the parent's window size changes then do
741 something like the following example::
743 import pexpect, struct, fcntl, termios, signal, sys
744 def sigwinch_passthrough (sig, data):
745 s = struct.pack("HHHH", 0, 0, 0, 0)
746 a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
747 termios.TIOCGWINSZ , s))
748 if not p.closed:
749 p.setwinsize(a[0],a[1])
751 # Note this 'p' is global and used in sigwinch_passthrough.
752 p = pexpect.spawn('/bin/bash')
753 signal.signal(signal.SIGWINCH, sigwinch_passthrough)
754 p.interact()
757 # Flush the buffer.
758 self.write_to_stdout(self.buffer)
759 self.stdout.flush()
760 self._buffer = self.buffer_type()
761 mode = tty.tcgetattr(self.STDIN_FILENO)
762 tty.setraw(self.STDIN_FILENO)
763 if escape_character is not None and PY3:
764 escape_character = escape_character.encode('latin-1')
765 try:
766 self.__interact_copy(escape_character, input_filter, output_filter)
767 finally:
768 tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
770 def __interact_writen(self, fd, data):
771 '''This is used by the interact() method.
774 while data != b'' and self.isalive():
775 n = os.write(fd, data)
776 data = data[n:]
778 def __interact_read(self, fd):
779 '''This is used by the interact() method.
782 return os.read(fd, 1000)
784 def __interact_copy(
785 self, escape_character=None, input_filter=None, output_filter=None
788 '''This is used by the interact() method.
791 while self.isalive():
792 if self.use_poll:
793 r = poll_ignore_interrupts([self.child_fd, self.STDIN_FILENO])
794 else:
795 r, w, e = select_ignore_interrupts(
796 [self.child_fd, self.STDIN_FILENO], [], []
798 if self.child_fd in r:
799 try:
800 data = self.__interact_read(self.child_fd)
801 except OSError as err:
802 if err.args[0] == errno.EIO:
803 # Linux-style EOF
804 break
805 raise
806 if data == b'':
807 # BSD-style EOF
808 break
809 if output_filter:
810 data = output_filter(data)
811 self._log(data, 'read')
812 os.write(self.STDOUT_FILENO, data)
813 if self.STDIN_FILENO in r:
814 data = self.__interact_read(self.STDIN_FILENO)
815 if input_filter:
816 data = input_filter(data)
817 i = -1
818 if escape_character is not None:
819 i = data.rfind(escape_character)
820 if i != -1:
821 data = data[:i]
822 if data:
823 self._log(data, 'send')
824 self.__interact_writen(self.child_fd, data)
825 break
826 self._log(data, 'send')
827 self.__interact_writen(self.child_fd, data)
830 def spawnu(*args, **kwargs):
831 """Deprecated: pass encoding to spawn() instead."""
832 kwargs.setdefault('encoding', 'utf-8')
833 return spawn(*args, **kwargs)