Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/pexpect/pty_spawn.py: 17%
310 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
1import os
2import sys
3import time
4import pty
5import tty
6import errno
7import signal
8from contextlib import contextmanager
10import ptyprocess
11from ptyprocess.ptyprocess import use_native_pty_fork
13from .exceptions import ExceptionPexpect, EOF, TIMEOUT
14from .spawnbase import SpawnBase
15from .utils import (
16 which, split_command_line, select_ignore_interrupts, poll_ignore_interrupts
17)
19@contextmanager
20def _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)
27PY3 = (sys.version_info[0] >= 3)
29class 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
188 '''
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.str_last_chars = 100
195 self.cwd = cwd
196 self.env = env
197 self.echo = echo
198 self.ignore_sighup = ignore_sighup
199 self.__irix_hack = sys.platform.lower().startswith('irix')
200 if command is None:
201 self.command = None
202 self.args = None
203 self.name = '<pexpect factory incomplete>'
204 else:
205 self._spawn(command, args, preexec_fn, dimensions)
206 self.use_poll = use_poll
208 def __str__(self):
209 '''This returns a human-readable string that represents the state of
210 the object. '''
212 s = []
213 s.append(repr(self))
214 s.append('command: ' + str(self.command))
215 s.append('args: %r' % (self.args,))
216 s.append('buffer (last %s chars): %r' % (self.str_last_chars,self.buffer[-self.str_last_chars:]))
217 s.append('before (last %s chars): %r' % (self.str_last_chars,self.before[-self.str_last_chars:] if self.before else ''))
218 s.append('after: %r' % (self.after,))
219 s.append('match: %r' % (self.match,))
220 s.append('match_index: ' + str(self.match_index))
221 s.append('exitstatus: ' + str(self.exitstatus))
222 if hasattr(self, 'ptyproc'):
223 s.append('flag_eof: ' + str(self.flag_eof))
224 s.append('pid: ' + str(self.pid))
225 s.append('child_fd: ' + str(self.child_fd))
226 s.append('closed: ' + str(self.closed))
227 s.append('timeout: ' + str(self.timeout))
228 s.append('delimiter: ' + str(self.delimiter))
229 s.append('logfile: ' + str(self.logfile))
230 s.append('logfile_read: ' + str(self.logfile_read))
231 s.append('logfile_send: ' + str(self.logfile_send))
232 s.append('maxread: ' + str(self.maxread))
233 s.append('ignorecase: ' + str(self.ignorecase))
234 s.append('searchwindowsize: ' + str(self.searchwindowsize))
235 s.append('delaybeforesend: ' + str(self.delaybeforesend))
236 s.append('delayafterclose: ' + str(self.delayafterclose))
237 s.append('delayafterterminate: ' + str(self.delayafterterminate))
238 return '\n'.join(s)
240 def _spawn(self, command, args=[], preexec_fn=None, dimensions=None):
241 '''This starts the given command in a child process. This does all the
242 fork/exec type of stuff for a pty. This is called by __init__. If args
243 is empty then command will be parsed (split on spaces) and args will be
244 set to parsed arguments. '''
246 # The pid and child_fd of this object get set by this method.
247 # Note that it is difficult for this method to fail.
248 # You cannot detect if the child process cannot start.
249 # So the only way you can tell if the child process started
250 # or not is to try to read from the file descriptor. If you get
251 # EOF immediately then it means that the child is already dead.
252 # That may not necessarily be bad because you may have spawned a child
253 # that performs some task; creates no stdout output; and then dies.
255 # If command is an int type then it may represent a file descriptor.
256 if isinstance(command, type(0)):
257 raise ExceptionPexpect('Command is an int type. ' +
258 'If this is a file descriptor then maybe you want to ' +
259 'use fdpexpect.fdspawn which takes an existing ' +
260 'file descriptor instead of a command string.')
262 if not isinstance(args, type([])):
263 raise TypeError('The argument, args, must be a list.')
265 if args == []:
266 self.args = split_command_line(command)
267 self.command = self.args[0]
268 else:
269 # Make a shallow copy of the args list.
270 self.args = args[:]
271 self.args.insert(0, command)
272 self.command = command
274 command_with_path = which(self.command, env=self.env)
275 if command_with_path is None:
276 raise ExceptionPexpect('The command was not found or was not ' +
277 'executable: %s.' % self.command)
278 self.command = command_with_path
279 self.args[0] = self.command
281 self.name = '<' + ' '.join(self.args) + '>'
283 assert self.pid is None, 'The pid member must be None.'
284 assert self.command is not None, 'The command member must not be None.'
286 kwargs = {'echo': self.echo, 'preexec_fn': preexec_fn}
287 if self.ignore_sighup:
288 def preexec_wrapper():
289 "Set SIGHUP to be ignored, then call the real preexec_fn"
290 signal.signal(signal.SIGHUP, signal.SIG_IGN)
291 if preexec_fn is not None:
292 preexec_fn()
293 kwargs['preexec_fn'] = preexec_wrapper
295 if dimensions is not None:
296 kwargs['dimensions'] = dimensions
298 if self.encoding is not None:
299 # Encode command line using the specified encoding
300 self.args = [a if isinstance(a, bytes) else a.encode(self.encoding)
301 for a in self.args]
303 self.ptyproc = self._spawnpty(self.args, env=self.env,
304 cwd=self.cwd, **kwargs)
306 self.pid = self.ptyproc.pid
307 self.child_fd = self.ptyproc.fd
310 self.terminated = False
311 self.closed = False
313 def _spawnpty(self, args, **kwargs):
314 '''Spawn a pty and return an instance of PtyProcess.'''
315 return ptyprocess.PtyProcess.spawn(args, **kwargs)
317 def close(self, force=True):
318 '''This closes the connection with the child application. Note that
319 calling close() more than once is valid. This emulates standard Python
320 behavior with files. Set force to True if you want to make sure that
321 the child is terminated (SIGKILL is sent if the child ignores SIGHUP
322 and SIGINT). '''
324 self.flush()
325 with _wrap_ptyprocess_err():
326 # PtyProcessError may be raised if it is not possible to terminate
327 # the child.
328 self.ptyproc.close(force=force)
329 self.isalive() # Update exit status from ptyproc
330 self.child_fd = -1
331 self.closed = True
333 def isatty(self):
334 '''This returns True if the file descriptor is open and connected to a
335 tty(-like) device, else False.
337 On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
338 the child pty may not appear as a terminal device. This means
339 methods such as setecho(), setwinsize(), getwinsize() may raise an
340 IOError. '''
342 return os.isatty(self.child_fd)
344 def waitnoecho(self, timeout=-1):
345 '''This waits until the terminal ECHO flag is set False. This returns
346 True if the echo mode is off. This returns False if the ECHO flag was
347 not set False before the timeout. This can be used to detect when the
348 child is waiting for a password. Usually a child application will turn
349 off echo mode when it is waiting for the user to enter a password. For
350 example, instead of expecting the "password:" prompt you can wait for
351 the child to set ECHO off::
353 p = pexpect.spawn('ssh user@example.com')
354 p.waitnoecho()
355 p.sendline(mypassword)
357 If timeout==-1 then this method will use the value in self.timeout.
358 If timeout==None then this method to block until ECHO flag is False.
359 '''
361 if timeout == -1:
362 timeout = self.timeout
363 if timeout is not None:
364 end_time = time.time() + timeout
365 while True:
366 if not self.getecho():
367 return True
368 if timeout < 0 and timeout is not None:
369 return False
370 if timeout is not None:
371 timeout = end_time - time.time()
372 time.sleep(0.1)
374 def getecho(self):
375 '''This returns the terminal echo mode. This returns True if echo is
376 on or False if echo is off. Child applications that are expecting you
377 to enter a password often set ECHO False. See waitnoecho().
379 Not supported on platforms where ``isatty()`` returns False. '''
380 return self.ptyproc.getecho()
382 def setecho(self, state):
383 '''This sets the terminal echo mode on or off. Note that anything the
384 child sent before the echo will be lost, so you should be sure that
385 your input buffer is empty before you call setecho(). For example, the
386 following will work as expected::
388 p = pexpect.spawn('cat') # Echo is on by default.
389 p.sendline('1234') # We expect see this twice from the child...
390 p.expect(['1234']) # ... once from the tty echo...
391 p.expect(['1234']) # ... and again from cat itself.
392 p.setecho(False) # Turn off tty echo
393 p.sendline('abcd') # We will set this only once (echoed by cat).
394 p.sendline('wxyz') # We will set this only once (echoed by cat)
395 p.expect(['abcd'])
396 p.expect(['wxyz'])
398 The following WILL NOT WORK because the lines sent before the setecho
399 will be lost::
401 p = pexpect.spawn('cat')
402 p.sendline('1234')
403 p.setecho(False) # Turn off tty echo
404 p.sendline('abcd') # We will set this only once (echoed by cat).
405 p.sendline('wxyz') # We will set this only once (echoed by cat)
406 p.expect(['1234'])
407 p.expect(['1234'])
408 p.expect(['abcd'])
409 p.expect(['wxyz'])
412 Not supported on platforms where ``isatty()`` returns False.
413 '''
414 return self.ptyproc.setecho(state)
416 def read_nonblocking(self, size=1, timeout=-1):
417 '''This reads at most size characters from the child application. It
418 includes a timeout. If the read does not complete within the timeout
419 period then a TIMEOUT exception is raised. If the end of file is read
420 then an EOF exception will be raised. If a logfile is specified, a
421 copy is written to that log.
423 If timeout is None then the read may block indefinitely.
424 If timeout is -1 then the self.timeout value is used. If timeout is 0
425 then the child is polled and if there is no data immediately ready
426 then this will raise a TIMEOUT exception.
428 The timeout refers only to the amount of time to read at least one
429 character. This is not affected by the 'size' parameter, so if you call
430 read_nonblocking(size=100, timeout=30) and only one character is
431 available right away then one character will be returned immediately.
432 It will not wait for 30 seconds for another 99 characters to come in.
434 On the other hand, if there are bytes available to read immediately,
435 all those bytes will be read (up to the buffer size). So, if the
436 buffer size is 1 megabyte and there is 1 megabyte of data available
437 to read, the buffer will be filled, regardless of timeout.
439 This is a wrapper around os.read(). It uses select.select() or
440 select.poll() to implement the timeout. '''
442 if self.closed:
443 raise ValueError('I/O operation on closed file.')
445 if self.use_poll:
446 def select(timeout):
447 return poll_ignore_interrupts([self.child_fd], timeout)
448 else:
449 def select(timeout):
450 return select_ignore_interrupts([self.child_fd], [], [], timeout)[0]
452 # If there is data available to read right now, read as much as
453 # we can. We do this to increase performance if there are a lot
454 # of bytes to be read. This also avoids calling isalive() too
455 # often. See also:
456 # * https://github.com/pexpect/pexpect/pull/304
457 # * http://trac.sagemath.org/ticket/10295
458 if select(0):
459 try:
460 incoming = super(spawn, self).read_nonblocking(size)
461 except EOF:
462 # Maybe the child is dead: update some attributes in that case
463 self.isalive()
464 raise
465 while len(incoming) < size and select(0):
466 try:
467 incoming += super(spawn, self).read_nonblocking(size - len(incoming))
468 except EOF:
469 # Maybe the child is dead: update some attributes in that case
470 self.isalive()
471 # Don't raise EOF, just return what we read so far.
472 return incoming
473 return incoming
475 if timeout == -1:
476 timeout = self.timeout
478 if not self.isalive():
479 # The process is dead, but there may or may not be data
480 # available to read. Note that some systems such as Solaris
481 # do not give an EOF when the child dies. In fact, you can
482 # still try to read from the child_fd -- it will block
483 # forever or until TIMEOUT. For that reason, it's important
484 # to do this check before calling select() with timeout.
485 if select(0):
486 return super(spawn, self).read_nonblocking(size)
487 self.flag_eof = True
488 raise EOF('End Of File (EOF). Braindead platform.')
489 elif self.__irix_hack:
490 # Irix takes a long time before it realizes a child was terminated.
491 # Make sure that the timeout is at least 2 seconds.
492 # FIXME So does this mean Irix systems are forced to always have
493 # FIXME a 2 second delay when calling read_nonblocking? That sucks.
494 if timeout is not None and timeout < 2:
495 timeout = 2
497 # Because of the select(0) check above, we know that no data
498 # is available right now. But if a non-zero timeout is given
499 # (possibly timeout=None), we call select() with a timeout.
500 if (timeout != 0) and select(timeout):
501 return super(spawn, self).read_nonblocking(size)
503 if not self.isalive():
504 # Some platforms, such as Irix, will claim that their
505 # processes are alive; timeout on the select; and
506 # then finally admit that they are not alive.
507 self.flag_eof = True
508 raise EOF('End of File (EOF). Very slow platform.')
509 else:
510 raise TIMEOUT('Timeout exceeded.')
512 def write(self, s):
513 '''This is similar to send() except that there is no return value.
514 '''
516 self.send(s)
518 def writelines(self, sequence):
519 '''This calls write() for each element in the sequence. The sequence
520 can be any iterable object producing strings, typically a list of
521 strings. This does not add line separators. There is no return value.
522 '''
524 for s in sequence:
525 self.write(s)
527 def send(self, s):
528 '''Sends string ``s`` to the child process, returning the number of
529 bytes written. If a logfile is specified, a copy is written to that
530 log.
532 The default terminal input mode is canonical processing unless set
533 otherwise by the child process. This allows backspace and other line
534 processing to be performed prior to transmitting to the receiving
535 program. As this is buffered, there is a limited size of such buffer.
537 On Linux systems, this is 4096 (defined by N_TTY_BUF_SIZE). All
538 other systems honor the POSIX.1 definition PC_MAX_CANON -- 1024
539 on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.
541 This value may be discovered using fpathconf(3)::
543 >>> from os import fpathconf
544 >>> print(fpathconf(0, 'PC_MAX_CANON'))
545 256
547 On such a system, only 256 bytes may be received per line. Any
548 subsequent bytes received will be discarded. BEL (``'\a'``) is then
549 sent to output if IMAXBEL (termios.h) is set by the tty driver.
550 This is usually enabled by default. Linux does not honor this as
551 an option -- it behaves as though it is always set on.
553 Canonical input processing may be disabled altogether by executing
554 a shell, then stty(1), before executing the final program::
556 >>> bash = pexpect.spawn('/bin/bash', echo=False)
557 >>> bash.sendline('stty -icanon')
558 >>> bash.sendline('base64')
559 >>> bash.sendline('x' * 5000)
560 '''
562 if self.delaybeforesend is not None:
563 time.sleep(self.delaybeforesend)
565 s = self._coerce_send_string(s)
566 self._log(s, 'send')
568 b = self._encoder.encode(s, final=False)
569 return os.write(self.child_fd, b)
571 def sendline(self, s=''):
572 '''Wraps send(), sending string ``s`` to child process, with
573 ``os.linesep`` automatically appended. Returns number of bytes
574 written. Only a limited number of bytes may be sent for each
575 line in the default terminal mode, see docstring of :meth:`send`.
576 '''
577 s = self._coerce_send_string(s)
578 return self.send(s + self.linesep)
580 def _log_control(self, s):
581 """Write control characters to the appropriate log files"""
582 if self.encoding is not None:
583 s = s.decode(self.encoding, 'replace')
584 self._log(s, 'send')
586 def sendcontrol(self, char):
587 '''Helper method that wraps send() with mnemonic access for sending control
588 character to the child (such as Ctrl-C or Ctrl-D). For example, to send
589 Ctrl-G (ASCII 7, bell, '\a')::
591 child.sendcontrol('g')
593 See also, sendintr() and sendeof().
594 '''
595 n, byte = self.ptyproc.sendcontrol(char)
596 self._log_control(byte)
597 return n
599 def sendeof(self):
600 '''This sends an EOF to the child. This sends a character which causes
601 the pending parent output buffer to be sent to the waiting child
602 program without waiting for end-of-line. If it is the first character
603 of the line, the read() in the user program returns 0, which signifies
604 end-of-file. This means to work as expected a sendeof() has to be
605 called at the beginning of a line. This method does not send a newline.
606 It is the responsibility of the caller to ensure the eof is sent at the
607 beginning of a line. '''
609 n, byte = self.ptyproc.sendeof()
610 self._log_control(byte)
612 def sendintr(self):
613 '''This sends a SIGINT to the child. It does not require
614 the SIGINT to be the first character on a line. '''
616 n, byte = self.ptyproc.sendintr()
617 self._log_control(byte)
619 @property
620 def flag_eof(self):
621 return self.ptyproc.flag_eof
623 @flag_eof.setter
624 def flag_eof(self, value):
625 self.ptyproc.flag_eof = value
627 def eof(self):
628 '''This returns True if the EOF exception was ever raised.
629 '''
630 return self.flag_eof
632 def terminate(self, force=False):
633 '''This forces a child process to terminate. It starts nicely with
634 SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
635 returns True if the child was terminated. This returns False if the
636 child could not be terminated. '''
638 if not self.isalive():
639 return True
640 try:
641 self.kill(signal.SIGHUP)
642 time.sleep(self.delayafterterminate)
643 if not self.isalive():
644 return True
645 self.kill(signal.SIGCONT)
646 time.sleep(self.delayafterterminate)
647 if not self.isalive():
648 return True
649 self.kill(signal.SIGINT)
650 time.sleep(self.delayafterterminate)
651 if not self.isalive():
652 return True
653 if force:
654 self.kill(signal.SIGKILL)
655 time.sleep(self.delayafterterminate)
656 if not self.isalive():
657 return True
658 else:
659 return False
660 return False
661 except OSError:
662 # I think there are kernel timing issues that sometimes cause
663 # this to happen. I think isalive() reports True, but the
664 # process is dead to the kernel.
665 # Make one last attempt to see if the kernel is up to date.
666 time.sleep(self.delayafterterminate)
667 if not self.isalive():
668 return True
669 else:
670 return False
672 def wait(self):
673 '''This waits until the child exits. This is a blocking call. This will
674 not read any data from the child, so this will block forever if the
675 child has unread output and has terminated. In other words, the child
676 may have printed output then called exit(), but, the child is
677 technically still alive until its output is read by the parent.
679 This method is non-blocking if :meth:`wait` has already been called
680 previously or :meth:`isalive` method returns False. It simply returns
681 the previously determined exit status.
682 '''
684 ptyproc = self.ptyproc
685 with _wrap_ptyprocess_err():
686 # exception may occur if "Is some other process attempting
687 # "job control with our child pid?"
688 exitstatus = ptyproc.wait()
689 self.status = ptyproc.status
690 self.exitstatus = ptyproc.exitstatus
691 self.signalstatus = ptyproc.signalstatus
692 self.terminated = True
694 return exitstatus
696 def isalive(self):
697 '''This tests if the child process is running or not. This is
698 non-blocking. If the child was terminated then this will read the
699 exitstatus or signalstatus of the child. This returns True if the child
700 process appears to be running or False if not. It can take literally
701 SECONDS for Solaris to return the right status. '''
703 ptyproc = self.ptyproc
704 with _wrap_ptyprocess_err():
705 alive = ptyproc.isalive()
707 if not alive:
708 self.status = ptyproc.status
709 self.exitstatus = ptyproc.exitstatus
710 self.signalstatus = ptyproc.signalstatus
711 self.terminated = True
713 return alive
715 def kill(self, sig):
717 '''This sends the given signal to the child application. In keeping
718 with UNIX tradition it has a misleading name. It does not necessarily
719 kill the child unless you send the right signal. '''
721 # Same as os.kill, but the pid is given for you.
722 if self.isalive():
723 os.kill(self.pid, sig)
725 def getwinsize(self):
726 '''This returns the terminal window size of the child tty. The return
727 value is a tuple of (rows, cols). '''
728 return self.ptyproc.getwinsize()
730 def setwinsize(self, rows, cols):
731 '''This sets the terminal window size of the child tty. This will cause
732 a SIGWINCH signal to be sent to the child. This does not change the
733 physical window size. It changes the size reported to TTY-aware
734 applications like vi or curses -- applications that respond to the
735 SIGWINCH signal. '''
736 return self.ptyproc.setwinsize(rows, cols)
739 def interact(self, escape_character=chr(29),
740 input_filter=None, output_filter=None):
742 '''This gives control of the child process to the interactive user (the
743 human at the keyboard). Keystrokes are sent to the child process, and
744 the stdout and stderr output of the child process is printed. This
745 simply echos the child stdout and child stderr to the real stdout and
746 it echos the real stdin to the child stdin. When the user types the
747 escape_character this method will return None. The escape_character
748 will not be transmitted. The default for escape_character is
749 entered as ``Ctrl - ]``, the very same as BSD telnet. To prevent
750 escaping, escape_character may be set to None.
752 If a logfile is specified, then the data sent and received from the
753 child process in interact mode is duplicated to the given log.
755 You may pass in optional input and output filter functions. These
756 functions should take bytes array and return bytes array too. Even
757 with ``encoding='utf-8'`` support, meth:`interact` will always pass
758 input_filter and output_filter bytes. You may need to wrap your
759 function to decode and encode back to UTF-8.
761 The output_filter will be passed all the output from the child process.
762 The input_filter will be passed all the keyboard input from the user.
763 The input_filter is run BEFORE the check for the escape_character.
765 Note that if you change the window size of the parent the SIGWINCH
766 signal will not be passed through to the child. If you want the child
767 window size to change when the parent's window size changes then do
768 something like the following example::
770 import pexpect, struct, fcntl, termios, signal, sys
771 def sigwinch_passthrough (sig, data):
772 s = struct.pack("HHHH", 0, 0, 0, 0)
773 a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
774 termios.TIOCGWINSZ , s))
775 if not p.closed:
776 p.setwinsize(a[0],a[1])
778 # Note this 'p' is global and used in sigwinch_passthrough.
779 p = pexpect.spawn('/bin/bash')
780 signal.signal(signal.SIGWINCH, sigwinch_passthrough)
781 p.interact()
782 '''
784 # Flush the buffer.
785 self.write_to_stdout(self.buffer)
786 self.stdout.flush()
787 self._buffer = self.buffer_type()
788 mode = tty.tcgetattr(self.STDIN_FILENO)
789 tty.setraw(self.STDIN_FILENO)
790 if escape_character is not None and PY3:
791 escape_character = escape_character.encode('latin-1')
792 try:
793 self.__interact_copy(escape_character, input_filter, output_filter)
794 finally:
795 tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
797 def __interact_writen(self, fd, data):
798 '''This is used by the interact() method.
799 '''
801 while data != b'' and self.isalive():
802 n = os.write(fd, data)
803 data = data[n:]
805 def __interact_read(self, fd):
806 '''This is used by the interact() method.
807 '''
809 return os.read(fd, 1000)
811 def __interact_copy(
812 self, escape_character=None, input_filter=None, output_filter=None
813 ):
815 '''This is used by the interact() method.
816 '''
818 while self.isalive():
819 if self.use_poll:
820 r = poll_ignore_interrupts([self.child_fd, self.STDIN_FILENO])
821 else:
822 r, w, e = select_ignore_interrupts(
823 [self.child_fd, self.STDIN_FILENO], [], []
824 )
825 if self.child_fd in r:
826 try:
827 data = self.__interact_read(self.child_fd)
828 except OSError as err:
829 if err.args[0] == errno.EIO:
830 # Linux-style EOF
831 break
832 raise
833 if data == b'':
834 # BSD-style EOF
835 break
836 if output_filter:
837 data = output_filter(data)
838 self._log(data, 'read')
839 os.write(self.STDOUT_FILENO, data)
840 if self.STDIN_FILENO in r:
841 data = self.__interact_read(self.STDIN_FILENO)
842 if input_filter:
843 data = input_filter(data)
844 i = -1
845 if escape_character is not None:
846 i = data.rfind(escape_character)
847 if i != -1:
848 data = data[:i]
849 if data:
850 self._log(data, 'send')
851 self.__interact_writen(self.child_fd, data)
852 break
853 self._log(data, 'send')
854 self.__interact_writen(self.child_fd, data)
857def spawnu(*args, **kwargs):
858 """Deprecated: pass encoding to spawn() instead."""
859 kwargs.setdefault('encoding', 'utf-8')
860 return spawn(*args, **kwargs)