15 import builtins
# Python 3
17 import __builtin__
as builtins
# Python 2
20 from pty
import (STDIN_FILENO
, CHILD
)
22 from .util
import which
, PtyProcessError
24 _platform
= sys
.platform
.lower()
26 # Solaris uses internal __fork_pty(). All others use pty.fork().
28 _platform
.startswith('solaris') or
29 _platform
.startswith('sunos'))
32 use_native_pty_fork
= False
33 from . import _fork_pty
35 use_native_pty_fork
= True
37 PY3
= sys
.version_info
[0] >= 3
46 class FileNotFoundError(OSError): pass
47 class TimeoutError(OSError): pass
49 _EOF
, _INTR
= None, None
52 """Set constants _EOF and _INTR.
54 This avoids doing potentially costly operations on module load.
57 if (_EOF
is not None) and (_INTR
is not None):
60 # inherit EOF and INTR definitions from controlling process.
62 from termios
import VEOF
, VINTR
64 for name
in 'stdin', 'stdout':
65 stream
= getattr(sys
, '__%s__' % name
, None)
66 if stream
is None or not hasattr(stream
, 'fileno'):
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
82 from termios
import CEOF
, CINTR
83 (intr
, eof
) = (CINTR
, CEOF
)
91 # setecho and setwinsize are pulled out here because on some platforms, we need
92 # to do this from the child before we exec()
94 def _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)'
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
))
105 attr
[3] = attr
[3] | termios
.ECHO
107 attr
[3] = attr
[3] & ~termios
.ECHO
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
))
118 def _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
)
128 class PtyProcess(object):
129 '''This class represents a process running in a pseudoterminal.
131 The main constructor is the :meth:`spawn` classmethod.
135 linesep
= os
.linesep
.encode('ascii')
136 crlf
= '\r\n'.encode('ascii')
139 def write_to_stdout(b
):
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'))
148 write_to_stdout
= sys
.stdout
.write
156 def __init__(self
, pid
, fd
):
157 _make_eof_intr() # Ensure _EOF and _INTR are calculated
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
166 self
.exitstatus
= None
167 self
.signalstatus
= None
168 # status returned by os.waitpid
170 self
.flag_eof
= False
171 # Used by close() to give kernel time to update process status.
173 self
.delayafterclose
= 0.1
174 # Used by terminate() to give kernel time to update process status.
176 self
.delayafterterminate
= 0.1
180 cls
, argv
, cwd
=None, env
=None, echo
=True, preexec_fn
=None,
181 dimensions
=(24, 80)):
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 # Note that it is difficult for this method to fail.
195 # You cannot detect if the child process cannot start.
196 # So the only way you can tell if the child process started
197 # or not is to try to read from the file descriptor. If you get
198 # EOF immediately then it means that the child is already dead.
199 # That may not necessarily be bad because you may have spawned a child
200 # that performs some task; creates no stdout output; and then dies.
202 if not isinstance(argv
, (list, tuple)):
203 raise TypeError("Expected a list or tuple for argv, got %r" % argv
)
205 # Shallow copy of argv so we can modify it
209 command_with_path
= which(command
)
210 if command_with_path
is None:
211 raise FileNotFoundError('The command was not found or was not ' +
212 'executable: %s.' % command
)
213 command
= command_with_path
216 # [issue #119] To prevent the case where exec fails and the user is
217 # stuck interacting with a python child process instead of whatever
218 # was expected, we implement the solution from
219 # http://stackoverflow.com/a/3703179 to pass the exception to the
222 # [issue #119] 1. Before forking, open a pipe in the parent process.
223 exec_err_pipe_read
, exec_err_pipe_write
= os
.pipe()
225 if use_native_pty_fork
:
228 # Use internal fork_pty, for Solaris
229 pid
, fd
= _fork_pty
.fork_pty()
231 # Some platforms must call setwinsize() and setecho() from the
232 # child process, and others from the primary process. We do both,
233 # allowing IOError for either.
238 _setwinsize(STDIN_FILENO
, *dimensions
)
239 except IOError as err
:
240 if err
.args
[0] not in (errno
.EINVAL
, errno
.ENOTTY
):
243 # disable echo if spawn argument echo was unset
246 _setecho(STDIN_FILENO
, False)
247 except (IOError, termios
.error
) as err
:
248 if err
.args
[0] not in (errno
.EINVAL
, errno
.ENOTTY
):
251 # [issue #119] 3. The child closes the reading end and sets the
252 # close-on-exec flag for the writing end.
253 os
.close(exec_err_pipe_read
)
254 fcntl
.fcntl(exec_err_pipe_write
, fcntl
.F_SETFD
, fcntl
.FD_CLOEXEC
)
256 # Do not allow child to inherit open file descriptors from parent,
257 # with the exception of the exec_err_pipe_write of the pipe
258 # Impose ceiling on max_fd: AIX bugfix for users with unlimited
259 # nofiles where resource.RLIMIT_NOFILE is 2^63-1 and os.closerange()
260 # occasionally raises out of range error
261 max_fd
= min(1048576, resource
.getrlimit(resource
.RLIMIT_NOFILE
)[0])
262 os
.closerange(3, exec_err_pipe_write
)
263 os
.closerange(exec_err_pipe_write
+1, max_fd
)
268 if preexec_fn
is not None:
271 except Exception as e
:
272 ename
= type(e
).__name
__
273 tosend
= '{}:0:{}'.format(ename
, str(e
))
275 tosend
= tosend
.encode('utf-8')
277 os
.write(exec_err_pipe_write
, tosend
)
278 os
.close(exec_err_pipe_write
)
283 os
.execv(command
, argv
)
285 os
.execvpe(command
, argv
, env
)
286 except OSError as err
:
287 # [issue #119] 5. If exec fails, the child writes the error
288 # code back to the parent using the pipe, then exits.
289 tosend
= 'OSError:{}:{}'.format(err
.errno
, str(err
))
291 tosend
= tosend
.encode('utf-8')
292 os
.write(exec_err_pipe_write
, tosend
)
293 os
.close(exec_err_pipe_write
)
294 os
._exit
(os
.EX_OSERR
)
299 # Set some informational attributes
304 inst
.launch_dir
= cwd
306 # [issue #119] 2. After forking, the parent closes the writing end
307 # of the pipe and reads from the reading end.
308 os
.close(exec_err_pipe_write
)
309 exec_err_data
= os
.read(exec_err_pipe_read
, 4096)
310 os
.close(exec_err_pipe_read
)
312 # [issue #119] 6. The parent reads eof (a zero-length read) if the
313 # child successfully performed exec, since close-on-exec made
314 # successful exec close the writing end of the pipe. Or, if exec
315 # failed, the parent reads the error code and can proceed
316 # accordingly. Either way, the parent blocks until the child calls
318 if len(exec_err_data
) != 0:
320 errclass
, errno_s
, errmsg
= exec_err_data
.split(b
':', 2)
321 exctype
= getattr(builtins
, errclass
.decode('ascii'), Exception)
323 exception
= exctype(errmsg
.decode('utf-8', 'replace'))
324 if exctype
is OSError:
325 exception
.errno
= int(errno_s
)
327 raise Exception('Subprocess failed, got bad error data: %r'
333 inst
.setwinsize(*dimensions
)
334 except IOError as err
:
335 if err
.args
[0] not in (errno
.EINVAL
, errno
.ENOTTY
, errno
.ENXIO
):
341 clsname
= type(self
).__name
__
342 if self
.argv
is not None:
343 args
= [repr(self
.argv
)]
344 if self
.env
is not None:
345 args
.append("env=%r" % self
.env
)
346 if self
.launch_dir
is not None:
347 args
.append("cwd=%r" % self
.launch_dir
)
349 return "{}.spawn({})".format(clsname
, ", ".join(args
))
352 return "{}(pid={}, fd={})".format(clsname
, self
.pid
, self
.fd
)
355 def _coerce_send_string(s
):
356 if not isinstance(s
, bytes
):
357 return s
.encode('utf-8')
361 def _coerce_read_string(s
):
365 '''This makes sure that no system resources are left open. Python only
366 garbage collects Python objects. OS file descriptors are not Python
367 objects, so they must be handled explicitly. If the child file
368 descriptor was opened outside of this class (passed to the constructor)
369 then this does not close it. '''
372 # It is possible for __del__ methods to execute during the
373 # teardown of the Python VM itself. Thus self.close() may
374 # trigger an exception because os.close may be None.
377 # which exception, shouldn't we catch explicitly .. ?
383 '''This returns the file descriptor of the pty for the child.
387 def close(self
, force
=True):
388 '''This closes the connection with the child application. Note that
389 calling close() more than once is valid. This emulates standard Python
390 behavior with files. Set force to True if you want to make sure that
391 the child is terminated (SIGKILL is sent if the child ignores SIGHUP
395 self
.fileobj
.close() # Closes the file descriptor
396 # Give kernel time to update process status.
397 time
.sleep(self
.delayafterclose
)
399 if not self
.terminate(force
):
400 raise PtyProcessError('Could not terminate the child.')
406 '''This does nothing. It is here to support the interface for a
407 File-like object. '''
412 '''This returns True if the file descriptor is open and connected to a
413 tty(-like) device, else False.
415 On SVR4-style platforms implementing streams, such as SunOS and HP-UX,
416 the child pty may not appear as a terminal device. This means
417 methods such as setecho(), setwinsize(), getwinsize() may raise an
420 return os
.isatty(self
.fd
)
422 def waitnoecho(self
, timeout
=None):
423 '''This waits until the terminal ECHO flag is set False. This returns
424 True if the echo mode is off. This returns False if the ECHO flag was
425 not set False before the timeout. This can be used to detect when the
426 child is waiting for a password. Usually a child application will turn
427 off echo mode when it is waiting for the user to enter a password. For
428 example, instead of expecting the "password:" prompt you can wait for
429 the child to set ECHO off::
431 p = pexpect.spawn('ssh user@example.com')
433 p.sendline(mypassword)
435 If timeout==None then this method to block until ECHO flag is False.
438 if timeout
is not None:
439 end_time
= time
.time() + timeout
441 if not self
.getecho():
443 if timeout
< 0 and timeout
is not None:
445 if timeout
is not None:
446 timeout
= end_time
- time
.time()
450 '''This returns the terminal echo mode. This returns True if echo is
451 on or False if echo is off. Child applications that are expecting you
452 to enter a password often set ECHO False. See waitnoecho().
454 Not supported on platforms where ``isatty()`` returns False. '''
457 attr
= termios
.tcgetattr(self
.fd
)
458 except termios
.error
as err
:
459 errmsg
= 'getecho() may not be called on this platform'
460 if err
.args
[0] == errno
.EINVAL
:
461 raise IOError(err
.args
[0], '%s: %s.' % (err
.args
[1], errmsg
))
464 self
.echo
= bool(attr
[3] & termios
.ECHO
)
467 def setecho(self
, state
):
468 '''This sets the terminal echo mode on or off. Note that anything the
469 child sent before the echo will be lost, so you should be sure that
470 your input buffer is empty before you call setecho(). For example, the
471 following will work as expected::
473 p = pexpect.spawn('cat') # Echo is on by default.
474 p.sendline('1234') # We expect see this twice from the child...
475 p.expect(['1234']) # ... once from the tty echo...
476 p.expect(['1234']) # ... and again from cat itself.
477 p.setecho(False) # Turn off tty echo
478 p.sendline('abcd') # We will set this only once (echoed by cat).
479 p.sendline('wxyz') # We will set this only once (echoed by cat)
483 The following WILL NOT WORK because the lines sent before the setecho
486 p = pexpect.spawn('cat')
488 p.setecho(False) # Turn off tty echo
489 p.sendline('abcd') # We will set this only once (echoed by cat).
490 p.sendline('wxyz') # We will set this only once (echoed by cat)
497 Not supported on platforms where ``isatty()`` returns False.
499 _setecho(self
.fd
, state
)
503 def read(self
, size
=1024):
504 """Read and return at most ``size`` bytes from the pty.
506 Can block if there is nothing to read. Raises :exc:`EOFError` if the
509 Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal
510 with the vagaries of EOF on platforms that do strange things, like IRIX
511 or older Solaris systems. It handles the errno=EIO pattern used on
512 Linux, and the empty-string return used on BSD platforms and (seemingly)
516 s
= self
.fileobj
.read1(size
)
517 except (OSError, IOError) as err
:
518 if err
.args
[0] == errno
.EIO
:
521 raise EOFError('End Of File (EOF). Exception style platform.')
524 # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
526 raise EOFError('End Of File (EOF). Empty string style platform.')
531 """Read one line from the pseudoterminal, and return it as unicode.
533 Can block if there is nothing to read. Raises :exc:`EOFError` if the
537 s
= self
.fileobj
.readline()
538 except (OSError, IOError) as err
:
539 if err
.args
[0] == errno
.EIO
:
542 raise EOFError('End Of File (EOF). Exception style platform.')
545 # BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
547 raise EOFError('End Of File (EOF). Empty string style platform.')
551 def _writeb(self
, b
, flush
=True):
552 n
= self
.fileobj
.write(b
)
557 def write(self
, s
, flush
=True):
558 """Write bytes to the pseudoterminal.
560 Returns the number of bytes written.
562 return self
._writeb
(s
, flush
=flush
)
564 def sendcontrol(self
, char
):
565 '''Helper method that wraps send() with mnemonic access for sending control
566 character to the child (such as Ctrl-C or Ctrl-D). For example, to send
567 Ctrl-G (ASCII 7, bell, '\a')::
569 child.sendcontrol('g')
571 See also, sendintr() and sendeof().
578 return self
._writeb
(byte
), byte
589 byte
= _byte(d
[char
])
590 return self
._writeb
(byte
), byte
593 '''This sends an EOF to the child. This sends a character which causes
594 the pending parent output buffer to be sent to the waiting child
595 program without waiting for end-of-line. If it is the first character
596 of the line, the read() in the user program returns 0, which signifies
597 end-of-file. This means to work as expected a sendeof() has to be
598 called at the beginning of a line. This method does not send a newline.
599 It is the responsibility of the caller to ensure the eof is sent at the
600 beginning of a line. '''
602 return self
._writeb
(_EOF
), _EOF
605 '''This sends a SIGINT to the child. It does not require
606 the SIGINT to be the first character on a line. '''
608 return self
._writeb
(_INTR
), _INTR
611 '''This returns True if the EOF exception was ever raised.
616 def terminate(self
, force
=False):
617 '''This forces a child process to terminate. It starts nicely with
618 SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
619 returns True if the child was terminated. This returns False if the
620 child could not be terminated. '''
622 if not self
.isalive():
625 self
.kill(signal
.SIGHUP
)
626 time
.sleep(self
.delayafterterminate
)
627 if not self
.isalive():
629 self
.kill(signal
.SIGCONT
)
630 time
.sleep(self
.delayafterterminate
)
631 if not self
.isalive():
633 self
.kill(signal
.SIGINT
)
634 time
.sleep(self
.delayafterterminate
)
635 if not self
.isalive():
638 self
.kill(signal
.SIGKILL
)
639 time
.sleep(self
.delayafterterminate
)
640 if not self
.isalive():
646 # I think there are kernel timing issues that sometimes cause
647 # this to happen. I think isalive() reports True, but the
648 # process is dead to the kernel.
649 # Make one last attempt to see if the kernel is up to date.
650 time
.sleep(self
.delayafterterminate
)
651 if not self
.isalive():
657 '''This waits until the child exits. This is a blocking call. This will
658 not read any data from the child, so this will block forever if the
659 child has unread output and has terminated. In other words, the child
660 may have printed output then called exit(), but, the child is
661 technically still alive until its output is read by the parent. '''
664 pid
, status
= os
.waitpid(self
.pid
, 0)
666 return self
.exitstatus
667 self
.exitstatus
= os
.WEXITSTATUS(status
)
668 if os
.WIFEXITED(status
):
670 self
.exitstatus
= os
.WEXITSTATUS(status
)
671 self
.signalstatus
= None
672 self
.terminated
= True
673 elif os
.WIFSIGNALED(status
):
675 self
.exitstatus
= None
676 self
.signalstatus
= os
.WTERMSIG(status
)
677 self
.terminated
= True
678 elif os
.WIFSTOPPED(status
): # pragma: no cover
679 # You can't call wait() on a child process in the stopped state.
680 raise PtyProcessError('Called wait() on a stopped child ' +
681 'process. This is not supported. Is some other ' +
682 'process attempting job control with our child pid?')
683 return self
.exitstatus
686 '''This tests if the child process is running or not. This is
687 non-blocking. If the child was terminated then this will read the
688 exitstatus or signalstatus of the child. This returns True if the child
689 process appears to be running or False if not. It can take literally
690 SECONDS for Solaris to return the right status. '''
696 # This is for Linux, which requires the blocking form
697 # of waitpid to get the status of a defunct process.
698 # This is super-lame. The flag_eof would have been set
699 # in read_nonblocking(), so this should be safe.
702 waitpid_options
= os
.WNOHANG
705 pid
, status
= os
.waitpid(self
.pid
, waitpid_options
)
708 if e
.errno
== errno
.ECHILD
:
709 raise PtyProcessError('isalive() encountered condition ' +
710 'where "terminated" is 0, but there was no child ' +
711 'process. Did someone else call waitpid() ' +
716 # I have to do this twice for Solaris.
717 # I can't even believe that I figured this out...
718 # If waitpid() returns 0 it means that no child process
719 # wishes to report, and the value of status is undefined.
722 ### os.WNOHANG) # Solaris!
723 pid
, status
= os
.waitpid(self
.pid
, waitpid_options
)
724 except OSError as e
: # pragma: no cover
725 # This should never happen...
726 if e
.errno
== errno
.ECHILD
:
727 raise PtyProcessError('isalive() encountered condition ' +
728 'that should never happen. There was no child ' +
729 'process. Did someone else call waitpid() ' +
734 # If pid is still 0 after two calls to waitpid() then the process
735 # really is alive. This seems to work on all platforms, except for
736 # Irix which seems to require a blocking call on waitpid or select,
737 # so I let read_nonblocking take care of this situation
738 # (unfortunately, this requires waiting through the timeout).
745 if os
.WIFEXITED(status
):
747 self
.exitstatus
= os
.WEXITSTATUS(status
)
748 self
.signalstatus
= None
749 self
.terminated
= True
750 elif os
.WIFSIGNALED(status
):
752 self
.exitstatus
= None
753 self
.signalstatus
= os
.WTERMSIG(status
)
754 self
.terminated
= True
755 elif os
.WIFSTOPPED(status
):
756 raise PtyProcessError('isalive() encountered condition ' +
757 'where child process is stopped. This is not ' +
758 'supported. Is some other process attempting ' +
759 'job control with our child pid?')
763 """Send the given signal to the child application.
765 In keeping with UNIX tradition it has a misleading name. It does not
766 necessarily kill the child unless you send the right signal. See the
767 :mod:`signal` module for constants representing signal numbers.
770 # Same as os.kill, but the pid is given for you.
772 os
.kill(self
.pid
, sig
)
774 def getwinsize(self
):
775 """Return the window size of the pseudoterminal as a tuple (rows, cols).
777 TIOCGWINSZ
= getattr(termios
, 'TIOCGWINSZ', 1074295912)
778 s
= struct
.pack('HHHH', 0, 0, 0, 0)
779 x
= fcntl
.ioctl(self
.fd
, TIOCGWINSZ
, s
)
780 return struct
.unpack('HHHH', x
)[0:2]
782 def setwinsize(self
, rows
, cols
):
783 """Set the terminal window size of the child tty.
785 This will cause a SIGWINCH signal to be sent to the child. This does not
786 change the physical window size. It changes the size reported to
787 TTY-aware applications like vi or curses -- applications that respond to
790 return _setwinsize(self
.fd
, rows
, cols
)
793 class PtyProcessUnicode(PtyProcess
):
794 """Unicode wrapper around a process running in a pseudoterminal.
796 This class exposes a similar interface to :class:`PtyProcess`, but its read
797 methods return unicode, and its :meth:`write` accepts unicode.
802 string_type
= unicode # analysis:ignore
804 def __init__(self
, pid
, fd
, encoding
='utf-8', codec_errors
='strict'):
805 super(PtyProcessUnicode
, self
).__init
__(pid
, fd
)
806 self
.encoding
= encoding
807 self
.codec_errors
= codec_errors
808 self
.decoder
= codecs
.getincrementaldecoder(encoding
)(errors
=codec_errors
)
810 def read(self
, size
=1024):
811 """Read at most ``size`` bytes from the pty, return them as unicode.
813 Can block if there is nothing to read. Raises :exc:`EOFError` if the
816 The size argument still refers to bytes, not unicode code points.
818 b
= super(PtyProcessUnicode
, self
).read(size
)
819 return self
.decoder
.decode(b
, final
=False)
822 """Read one line from the pseudoterminal, and return it as unicode.
824 Can block if there is nothing to read. Raises :exc:`EOFError` if the
827 b
= super(PtyProcessUnicode
, self
).readline()
828 return self
.decoder
.decode(b
, final
=False)
831 """Write the unicode string ``s`` to the pseudoterminal.
833 Returns the number of bytes written.
835 b
= s
.encode(self
.encoding
)
836 return super(PtyProcessUnicode
, self
).write(b
)