Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/ptyprocess/ptyprocess.py: 18%
411 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 codecs
2import errno
3import fcntl
4import io
5import os
6import pty
7import resource
8import signal
9import struct
10import sys
11import termios
12import time
14try:
15 import builtins # Python 3
16except ImportError:
17 import __builtin__ as builtins # Python 2
19# Constants
20from pty import (STDIN_FILENO, CHILD)
22from .util import which, PtyProcessError
24_platform = sys.platform.lower()
26# Solaris uses internal __fork_pty(). All others use pty.fork().
27_is_solaris = (
28 _platform.startswith('solaris') or
29 _platform.startswith('sunos'))
31if _is_solaris:
32 use_native_pty_fork = False
33 from . import _fork_pty
34else:
35 use_native_pty_fork = True
37PY3 = sys.version_info[0] >= 3
39if PY3:
40 def _byte(i):
41 return bytes([i])
42else:
43 def _byte(i):
44 return chr(i)
46 class FileNotFoundError(OSError): pass
47 class TimeoutError(OSError): pass
49_EOF, _INTR = None, None
51def _make_eof_intr():
52 """Set constants _EOF and _INTR.
54 This avoids doing potentially costly operations on module load.
55 """
56 global _EOF, _INTR
57 if (_EOF is not None) and (_INTR is not None):
58 return
60 # inherit EOF and INTR definitions from controlling process.
61 try:
62 from termios import VEOF, VINTR
63 fd = None
64 for name in 'stdin', 'stdout':
65 stream = getattr(sys, '__%s__' % name, None)
66 if stream is None or not hasattr(stream, 'fileno'):
67 continue
68 try:
69 fd = stream.fileno()
70 except ValueError:
71 continue
72 if fd is None:
73 # no fd, raise ValueError to fallback on CEOF, CINTR
74 raise ValueError("No stream has a fileno")
75 intr = ord(termios.tcgetattr(fd)[6][VINTR])
76 eof = ord(termios.tcgetattr(fd)[6][VEOF])
77 except (ImportError, OSError, IOError, ValueError, termios.error):
78 # unless the controlling process is also not a terminal,
79 # such as cron(1), or when stdin and stdout are both closed.
80 # Fall-back to using CEOF and CINTR. There
81 try:
82 from termios import CEOF, CINTR
83 (intr, eof) = (CINTR, CEOF)
84 except ImportError:
85 # ^C, ^D
86 (intr, eof) = (3, 4)
88 _INTR = _byte(intr)
89 _EOF = _byte(eof)
91# setecho and setwinsize are pulled out here because on some platforms, we need
92# to do this from the child before we exec()
94def _setecho(fd, state):
95 errmsg = 'setecho() may not be called on this platform (it may still be possible to enable/disable echo when spawning the child process)'
97 try:
98 attr = termios.tcgetattr(fd)
99 except termios.error as err:
100 if err.args[0] == errno.EINVAL:
101 raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
102 raise
104 if state:
105 attr[3] = attr[3] | termios.ECHO
106 else:
107 attr[3] = attr[3] & ~termios.ECHO
109 try:
110 # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent and
111 # blocked on some platforms. TCSADRAIN would probably be ideal.
112 termios.tcsetattr(fd, termios.TCSANOW, attr)
113 except IOError as err:
114 if err.args[0] == errno.EINVAL:
115 raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
116 raise
118def _setwinsize(fd, rows, cols):
119 # Some very old platforms have a bug that causes the value for
120 # termios.TIOCSWINSZ to be truncated. There was a hack here to work
121 # around this, but it caused problems with newer platforms so has been
122 # removed. For details see https://github.com/pexpect/pexpect/issues/39
123 TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
124 # Note, assume ws_xpixel and ws_ypixel are zero.
125 s = struct.pack('HHHH', rows, cols, 0, 0)
126 fcntl.ioctl(fd, TIOCSWINSZ, s)
128class PtyProcess(object):
129 '''This class represents a process running in a pseudoterminal.
131 The main constructor is the :meth:`spawn` classmethod.
132 '''
133 string_type = bytes
134 if PY3:
135 linesep = os.linesep.encode('ascii')
136 crlf = '\r\n'.encode('ascii')
138 @staticmethod
139 def write_to_stdout(b):
140 try:
141 return sys.stdout.buffer.write(b)
142 except AttributeError:
143 # If stdout has been replaced, it may not have .buffer
144 return sys.stdout.write(b.decode('ascii', 'replace'))
145 else:
146 linesep = os.linesep
147 crlf = '\r\n'
148 write_to_stdout = sys.stdout.write
150 encoding = None
152 argv = None
153 env = None
154 launch_dir = None
156 def __init__(self, pid, fd):
157 _make_eof_intr() # Ensure _EOF and _INTR are calculated
158 self.pid = pid
159 self.fd = fd
160 readf = io.open(fd, 'rb', buffering=0)
161 writef = io.open(fd, 'wb', buffering=0, closefd=False)
162 self.fileobj = io.BufferedRWPair(readf, writef)
164 self.terminated = False
165 self.closed = False
166 self.exitstatus = None
167 self.signalstatus = None
168 # status returned by os.waitpid
169 self.status = None
170 self.flag_eof = False
171 # Used by close() to give kernel time to update process status.
172 # Time in seconds.
173 self.delayafterclose = 0.1
174 # Used by terminate() to give kernel time to update process status.
175 # Time in seconds.
176 self.delayafterterminate = 0.1
178 @classmethod
179 def spawn(
180 cls, argv, cwd=None, env=None, echo=True, preexec_fn=None,
181 dimensions=(24, 80), pass_fds=()):
182 '''Start the given command in a child process in a pseudo terminal.
184 This does all the fork/exec type of stuff for a pty, and returns an
185 instance of PtyProcess.
187 If preexec_fn is supplied, it will be called with no arguments in the
188 child process before exec-ing the specified command.
189 It may, for instance, set signal handlers to SIG_DFL or SIG_IGN.
191 Dimensions of the psuedoterminal used for the subprocess can be
192 specified as a tuple (rows, cols), or the default (24, 80) will be used.
194 By default, all file descriptors except 0, 1 and 2 are closed. This
195 behavior can be overridden with pass_fds, a list of file descriptors to
196 keep open between the parent and the child.
197 '''
198 # Note that it is difficult for this method to fail.
199 # You cannot detect if the child process cannot start.
200 # So the only way you can tell if the child process started
201 # or not is to try to read from the file descriptor. If you get
202 # EOF immediately then it means that the child is already dead.
203 # That may not necessarily be bad because you may have spawned a child
204 # that performs some task; creates no stdout output; and then dies.
206 if not isinstance(argv, (list, tuple)):
207 raise TypeError("Expected a list or tuple for argv, got %r" % argv)
209 # Shallow copy of argv so we can modify it
210 argv = argv[:]
211 command = argv[0]
213 command_with_path = which(command)
214 if command_with_path is None:
215 raise FileNotFoundError('The command was not found or was not ' +
216 'executable: %s.' % command)
217 command = command_with_path
218 argv[0] = command
220 # [issue #119] To prevent the case where exec fails and the user is
221 # stuck interacting with a python child process instead of whatever
222 # was expected, we implement the solution from
223 # http://stackoverflow.com/a/3703179 to pass the exception to the
224 # parent process
226 # [issue #119] 1. Before forking, open a pipe in the parent process.
227 exec_err_pipe_read, exec_err_pipe_write = os.pipe()
229 if use_native_pty_fork:
230 pid, fd = pty.fork()
231 else:
232 # Use internal fork_pty, for Solaris
233 pid, fd = _fork_pty.fork_pty()
235 # Some platforms must call setwinsize() and setecho() from the
236 # child process, and others from the master process. We do both,
237 # allowing IOError for either.
239 if pid == CHILD:
240 # set window size
241 try:
242 _setwinsize(STDIN_FILENO, *dimensions)
243 except IOError as err:
244 if err.args[0] not in (errno.EINVAL, errno.ENOTTY):
245 raise
247 # disable echo if spawn argument echo was unset
248 if not echo:
249 try:
250 _setecho(STDIN_FILENO, False)
251 except (IOError, termios.error) as err:
252 if err.args[0] not in (errno.EINVAL, errno.ENOTTY):
253 raise
255 # [issue #119] 3. The child closes the reading end and sets the
256 # close-on-exec flag for the writing end.
257 os.close(exec_err_pipe_read)
258 fcntl.fcntl(exec_err_pipe_write, fcntl.F_SETFD, fcntl.FD_CLOEXEC)
260 # Do not allow child to inherit open file descriptors from parent,
261 # with the exception of the exec_err_pipe_write of the pipe
262 # and pass_fds.
263 # Impose ceiling on max_fd: AIX bugfix for users with unlimited
264 # nofiles where resource.RLIMIT_NOFILE is 2^63-1 and os.closerange()
265 # occasionally raises out of range error
266 max_fd = min(1048576, resource.getrlimit(resource.RLIMIT_NOFILE)[0])
267 spass_fds = sorted(set(pass_fds) | {exec_err_pipe_write})
268 for pair in zip([2] + spass_fds, spass_fds + [max_fd]):
269 os.closerange(pair[0]+1, pair[1])
271 if cwd is not None:
272 os.chdir(cwd)
274 if preexec_fn is not None:
275 try:
276 preexec_fn()
277 except Exception as e:
278 ename = type(e).__name__
279 tosend = '{}:0:{}'.format(ename, str(e))
280 if PY3:
281 tosend = tosend.encode('utf-8')
283 os.write(exec_err_pipe_write, tosend)
284 os.close(exec_err_pipe_write)
285 os._exit(1)
287 try:
288 if env is None:
289 os.execv(command, argv)
290 else:
291 os.execvpe(command, argv, env)
292 except OSError as err:
293 # [issue #119] 5. If exec fails, the child writes the error
294 # code back to the parent using the pipe, then exits.
295 tosend = 'OSError:{}:{}'.format(err.errno, str(err))
296 if PY3:
297 tosend = tosend.encode('utf-8')
298 os.write(exec_err_pipe_write, tosend)
299 os.close(exec_err_pipe_write)
300 os._exit(os.EX_OSERR)
302 # Parent
303 inst = cls(pid, fd)
305 # Set some informational attributes
306 inst.argv = argv
307 if env is not None:
308 inst.env = env
309 if cwd is not None:
310 inst.launch_dir = cwd
312 # [issue #119] 2. After forking, the parent closes the writing end
313 # of the pipe and reads from the reading end.
314 os.close(exec_err_pipe_write)
315 exec_err_data = os.read(exec_err_pipe_read, 4096)
316 os.close(exec_err_pipe_read)
318 # [issue #119] 6. The parent reads eof (a zero-length read) if the
319 # child successfully performed exec, since close-on-exec made
320 # successful exec close the writing end of the pipe. Or, if exec
321 # failed, the parent reads the error code and can proceed
322 # accordingly. Either way, the parent blocks until the child calls
323 # exec.
324 if len(exec_err_data) != 0:
325 try:
326 errclass, errno_s, errmsg = exec_err_data.split(b':', 2)
327 exctype = getattr(builtins, errclass.decode('ascii'), Exception)
329 exception = exctype(errmsg.decode('utf-8', 'replace'))
330 if exctype is OSError:
331 exception.errno = int(errno_s)
332 except:
333 raise Exception('Subprocess failed, got bad error data: %r'
334 % exec_err_data)
335 else:
336 raise exception
338 try:
339 inst.setwinsize(*dimensions)
340 except IOError as err:
341 if err.args[0] not in (errno.EINVAL, errno.ENOTTY, errno.ENXIO):
342 raise
344 return inst
346 def __repr__(self):
347 clsname = type(self).__name__
348 if self.argv is not None:
349 args = [repr(self.argv)]
350 if self.env is not None:
351 args.append("env=%r" % self.env)
352 if self.launch_dir is not None:
353 args.append("cwd=%r" % self.launch_dir)
355 return "{}.spawn({})".format(clsname, ", ".join(args))
357 else:
358 return "{}(pid={}, fd={})".format(clsname, self.pid, self.fd)
360 @staticmethod
361 def _coerce_send_string(s):
362 if not isinstance(s, bytes):
363 return s.encode('utf-8')
364 return s
366 @staticmethod
367 def _coerce_read_string(s):
368 return s
370 def __del__(self):
371 '''This makes sure that no system resources are left open. Python only
372 garbage collects Python objects. OS file descriptors are not Python
373 objects, so they must be handled explicitly. If the child file
374 descriptor was opened outside of this class (passed to the constructor)
375 then this does not close it. '''
377 if not self.closed:
378 # It is possible for __del__ methods to execute during the
379 # teardown of the Python VM itself. Thus self.close() may
380 # trigger an exception because os.close may be None.
381 try:
382 self.close()
383 # which exception, shouldn't we catch explicitly .. ?
384 except:
385 pass
388 def fileno(self):
389 '''This returns the file descriptor of the pty for the child.
390 '''
391 return self.fd
393 def close(self, force=True):
394 '''This closes the connection with the child application. Note that
395 calling close() more than once is valid. This emulates standard Python
396 behavior with files. Set force to True if you want to make sure that
397 the child is terminated (SIGKILL is sent if the child ignores SIGHUP
398 and SIGINT). '''
399 if not self.closed:
400 self.flush()
401 self.fileobj.close() # Closes the file descriptor
402 # Give kernel time to update process status.
403 time.sleep(self.delayafterclose)
404 if self.isalive():
405 if not self.terminate(force):
406 raise PtyProcessError('Could not terminate the child.')
407 self.fd = -1
408 self.closed = True
409 #self.pid = None
411 def flush(self):
412 '''This does nothing. It is here to support the interface for a
413 File-like object. '''
415 pass
417 def isatty(self):
418 '''This returns True if the file descriptor is open and connected to a
419 tty(-like) device, else False.
421 On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
422 the child pty may not appear as a terminal device. This means
423 methods such as setecho(), setwinsize(), getwinsize() may raise an
424 IOError. '''
426 return os.isatty(self.fd)
428 def waitnoecho(self, timeout=None):
429 '''This waits until the terminal ECHO flag is set False. This returns
430 True if the echo mode is off. This returns False if the ECHO flag was
431 not set False before the timeout. This can be used to detect when the
432 child is waiting for a password. Usually a child application will turn
433 off echo mode when it is waiting for the user to enter a password. For
434 example, instead of expecting the "password:" prompt you can wait for
435 the child to set ECHO off::
437 p = pexpect.spawn('ssh user@example.com')
438 p.waitnoecho()
439 p.sendline(mypassword)
441 If timeout==None then this method to block until ECHO flag is False.
442 '''
444 if timeout is not None:
445 end_time = time.time() + timeout
446 while True:
447 if not self.getecho():
448 return True
449 if timeout < 0 and timeout is not None:
450 return False
451 if timeout is not None:
452 timeout = end_time - time.time()
453 time.sleep(0.1)
455 def getecho(self):
456 '''This returns the terminal echo mode. This returns True if echo is
457 on or False if echo is off. Child applications that are expecting you
458 to enter a password often set ECHO False. See waitnoecho().
460 Not supported on platforms where ``isatty()`` returns False. '''
462 try:
463 attr = termios.tcgetattr(self.fd)
464 except termios.error as err:
465 errmsg = 'getecho() may not be called on this platform'
466 if err.args[0] == errno.EINVAL:
467 raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
468 raise
470 self.echo = bool(attr[3] & termios.ECHO)
471 return self.echo
473 def setecho(self, state):
474 '''This sets the terminal echo mode on or off. Note that anything the
475 child sent before the echo will be lost, so you should be sure that
476 your input buffer is empty before you call setecho(). For example, the
477 following will work as expected::
479 p = pexpect.spawn('cat') # Echo is on by default.
480 p.sendline('1234') # We expect see this twice from the child...
481 p.expect(['1234']) # ... once from the tty echo...
482 p.expect(['1234']) # ... and again from cat itself.
483 p.setecho(False) # Turn off tty echo
484 p.sendline('abcd') # We will set this only once (echoed by cat).
485 p.sendline('wxyz') # We will set this only once (echoed by cat)
486 p.expect(['abcd'])
487 p.expect(['wxyz'])
489 The following WILL NOT WORK because the lines sent before the setecho
490 will be lost::
492 p = pexpect.spawn('cat')
493 p.sendline('1234')
494 p.setecho(False) # Turn off tty echo
495 p.sendline('abcd') # We will set this only once (echoed by cat).
496 p.sendline('wxyz') # We will set this only once (echoed by cat)
497 p.expect(['1234'])
498 p.expect(['1234'])
499 p.expect(['abcd'])
500 p.expect(['wxyz'])
503 Not supported on platforms where ``isatty()`` returns False.
504 '''
505 _setecho(self.fd, state)
507 self.echo = state
509 def read(self, size=1024):
510 """Read and return at most ``size`` bytes from the pty.
512 Can block if there is nothing to read. Raises :exc:`EOFError` if the
513 terminal was closed.
515 Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal
516 with the vagaries of EOF on platforms that do strange things, like IRIX
517 or older Solaris systems. It handles the errno=EIO pattern used on
518 Linux, and the empty-string return used on BSD platforms and (seemingly)
519 on recent Solaris.
520 """
521 try:
522 s = self.fileobj.read1(size)
523 except (OSError, IOError) as err:
524 if err.args[0] == errno.EIO:
525 # Linux-style EOF
526 self.flag_eof = True
527 raise EOFError('End Of File (EOF). Exception style platform.')
528 raise
529 if s == b'':
530 # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
531 self.flag_eof = True
532 raise EOFError('End Of File (EOF). Empty string style platform.')
534 return s
536 def readline(self):
537 """Read one line from the pseudoterminal, and return it as unicode.
539 Can block if there is nothing to read. Raises :exc:`EOFError` if the
540 terminal was closed.
541 """
542 try:
543 s = self.fileobj.readline()
544 except (OSError, IOError) as err:
545 if err.args[0] == errno.EIO:
546 # Linux-style EOF
547 self.flag_eof = True
548 raise EOFError('End Of File (EOF). Exception style platform.')
549 raise
550 if s == b'':
551 # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
552 self.flag_eof = True
553 raise EOFError('End Of File (EOF). Empty string style platform.')
555 return s
557 def _writeb(self, b, flush=True):
558 n = self.fileobj.write(b)
559 if flush:
560 self.fileobj.flush()
561 return n
563 def write(self, s, flush=True):
564 """Write bytes to the pseudoterminal.
566 Returns the number of bytes written.
567 """
568 return self._writeb(s, flush=flush)
570 def sendcontrol(self, char):
571 '''Helper method that wraps send() with mnemonic access for sending control
572 character to the child (such as Ctrl-C or Ctrl-D). For example, to send
573 Ctrl-G (ASCII 7, bell, '\a')::
575 child.sendcontrol('g')
577 See also, sendintr() and sendeof().
578 '''
579 char = char.lower()
580 a = ord(char)
581 if 97 <= a <= 122:
582 a = a - ord('a') + 1
583 byte = _byte(a)
584 return self._writeb(byte), byte
585 d = {'@': 0, '`': 0,
586 '[': 27, '{': 27,
587 '\\': 28, '|': 28,
588 ']': 29, '}': 29,
589 '^': 30, '~': 30,
590 '_': 31,
591 '?': 127}
592 if char not in d:
593 return 0, b''
595 byte = _byte(d[char])
596 return self._writeb(byte), byte
598 def sendeof(self):
599 '''This sends an EOF to the child. This sends a character which causes
600 the pending parent output buffer to be sent to the waiting child
601 program without waiting for end-of-line. If it is the first character
602 of the line, the read() in the user program returns 0, which signifies
603 end-of-file. This means to work as expected a sendeof() has to be
604 called at the beginning of a line. This method does not send a newline.
605 It is the responsibility of the caller to ensure the eof is sent at the
606 beginning of a line. '''
608 return self._writeb(_EOF), _EOF
610 def sendintr(self):
611 '''This sends a SIGINT to the child. It does not require
612 the SIGINT to be the first character on a line. '''
614 return self._writeb(_INTR), _INTR
616 def eof(self):
617 '''This returns True if the EOF exception was ever raised.
618 '''
620 return self.flag_eof
622 def terminate(self, force=False):
623 '''This forces a child process to terminate. It starts nicely with
624 SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
625 returns True if the child was terminated. This returns False if the
626 child could not be terminated. '''
628 if not self.isalive():
629 return True
630 try:
631 self.kill(signal.SIGHUP)
632 time.sleep(self.delayafterterminate)
633 if not self.isalive():
634 return True
635 self.kill(signal.SIGCONT)
636 time.sleep(self.delayafterterminate)
637 if not self.isalive():
638 return True
639 self.kill(signal.SIGINT)
640 time.sleep(self.delayafterterminate)
641 if not self.isalive():
642 return True
643 if force:
644 self.kill(signal.SIGKILL)
645 time.sleep(self.delayafterterminate)
646 if not self.isalive():
647 return True
648 else:
649 return False
650 return False
651 except OSError:
652 # I think there are kernel timing issues that sometimes cause
653 # this to happen. I think isalive() reports True, but the
654 # process is dead to the kernel.
655 # Make one last attempt to see if the kernel is up to date.
656 time.sleep(self.delayafterterminate)
657 if not self.isalive():
658 return True
659 else:
660 return False
662 def wait(self):
663 '''This waits until the child exits. This is a blocking call. This will
664 not read any data from the child, so this will block forever if the
665 child has unread output and has terminated. In other words, the child
666 may have printed output then called exit(), but, the child is
667 technically still alive until its output is read by the parent. '''
669 if self.isalive():
670 pid, status = os.waitpid(self.pid, 0)
671 else:
672 return self.exitstatus
673 self.exitstatus = os.WEXITSTATUS(status)
674 if os.WIFEXITED(status):
675 self.status = status
676 self.exitstatus = os.WEXITSTATUS(status)
677 self.signalstatus = None
678 self.terminated = True
679 elif os.WIFSIGNALED(status):
680 self.status = status
681 self.exitstatus = None
682 self.signalstatus = os.WTERMSIG(status)
683 self.terminated = True
684 elif os.WIFSTOPPED(status): # pragma: no cover
685 # You can't call wait() on a child process in the stopped state.
686 raise PtyProcessError('Called wait() on a stopped child ' +
687 'process. This is not supported. Is some other ' +
688 'process attempting job control with our child pid?')
689 return self.exitstatus
691 def isalive(self):
692 '''This tests if the child process is running or not. This is
693 non-blocking. If the child was terminated then this will read the
694 exitstatus or signalstatus of the child. This returns True if the child
695 process appears to be running or False if not. It can take literally
696 SECONDS for Solaris to return the right status. '''
698 if self.terminated:
699 return False
701 if self.flag_eof:
702 # This is for Linux, which requires the blocking form
703 # of waitpid to get the status of a defunct process.
704 # This is super-lame. The flag_eof would have been set
705 # in read_nonblocking(), so this should be safe.
706 waitpid_options = 0
707 else:
708 waitpid_options = os.WNOHANG
710 try:
711 pid, status = os.waitpid(self.pid, waitpid_options)
712 except OSError as e:
713 # No child processes
714 if e.errno == errno.ECHILD:
715 raise PtyProcessError('isalive() encountered condition ' +
716 'where "terminated" is 0, but there was no child ' +
717 'process. Did someone else call waitpid() ' +
718 'on our process?')
719 else:
720 raise
722 # I have to do this twice for Solaris.
723 # I can't even believe that I figured this out...
724 # If waitpid() returns 0 it means that no child process
725 # wishes to report, and the value of status is undefined.
726 if pid == 0:
727 try:
728 ### os.WNOHANG) # Solaris!
729 pid, status = os.waitpid(self.pid, waitpid_options)
730 except OSError as e: # pragma: no cover
731 # This should never happen...
732 if e.errno == errno.ECHILD:
733 raise PtyProcessError('isalive() encountered condition ' +
734 'that should never happen. There was no child ' +
735 'process. Did someone else call waitpid() ' +
736 'on our process?')
737 else:
738 raise
740 # If pid is still 0 after two calls to waitpid() then the process
741 # really is alive. This seems to work on all platforms, except for
742 # Irix which seems to require a blocking call on waitpid or select,
743 # so I let read_nonblocking take care of this situation
744 # (unfortunately, this requires waiting through the timeout).
745 if pid == 0:
746 return True
748 if pid == 0:
749 return True
751 if os.WIFEXITED(status):
752 self.status = status
753 self.exitstatus = os.WEXITSTATUS(status)
754 self.signalstatus = None
755 self.terminated = True
756 elif os.WIFSIGNALED(status):
757 self.status = status
758 self.exitstatus = None
759 self.signalstatus = os.WTERMSIG(status)
760 self.terminated = True
761 elif os.WIFSTOPPED(status):
762 raise PtyProcessError('isalive() encountered condition ' +
763 'where child process is stopped. This is not ' +
764 'supported. Is some other process attempting ' +
765 'job control with our child pid?')
766 return False
768 def kill(self, sig):
769 """Send the given signal to the child application.
771 In keeping with UNIX tradition it has a misleading name. It does not
772 necessarily kill the child unless you send the right signal. See the
773 :mod:`signal` module for constants representing signal numbers.
774 """
776 # Same as os.kill, but the pid is given for you.
777 if self.isalive():
778 os.kill(self.pid, sig)
780 def getwinsize(self):
781 """Return the window size of the pseudoterminal as a tuple (rows, cols).
782 """
783 TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
784 s = struct.pack('HHHH', 0, 0, 0, 0)
785 x = fcntl.ioctl(self.fd, TIOCGWINSZ, s)
786 return struct.unpack('HHHH', x)[0:2]
788 def setwinsize(self, rows, cols):
789 """Set the terminal window size of the child tty.
791 This will cause a SIGWINCH signal to be sent to the child. This does not
792 change the physical window size. It changes the size reported to
793 TTY-aware applications like vi or curses -- applications that respond to
794 the SIGWINCH signal.
795 """
796 return _setwinsize(self.fd, rows, cols)
799class PtyProcessUnicode(PtyProcess):
800 """Unicode wrapper around a process running in a pseudoterminal.
802 This class exposes a similar interface to :class:`PtyProcess`, but its read
803 methods return unicode, and its :meth:`write` accepts unicode.
804 """
805 if PY3:
806 string_type = str
807 else:
808 string_type = unicode # analysis:ignore
810 def __init__(self, pid, fd, encoding='utf-8', codec_errors='strict'):
811 super(PtyProcessUnicode, self).__init__(pid, fd)
812 self.encoding = encoding
813 self.codec_errors = codec_errors
814 self.decoder = codecs.getincrementaldecoder(encoding)(errors=codec_errors)
816 def read(self, size=1024):
817 """Read at most ``size`` bytes from the pty, return them as unicode.
819 Can block if there is nothing to read. Raises :exc:`EOFError` if the
820 terminal was closed.
822 The size argument still refers to bytes, not unicode code points.
823 """
824 b = super(PtyProcessUnicode, self).read(size)
825 return self.decoder.decode(b, final=False)
827 def readline(self):
828 """Read one line from the pseudoterminal, and return it as unicode.
830 Can block if there is nothing to read. Raises :exc:`EOFError` if the
831 terminal was closed.
832 """
833 b = super(PtyProcessUnicode, self).readline()
834 return self.decoder.decode(b, final=False)
836 def write(self, s):
837 """Write the unicode string ``s`` to the pseudoterminal.
839 Returns the number of bytes written.
840 """
841 b = s.encode(self.encoding)
842 return super(PtyProcessUnicode, self).write(b)