{
    "content": [
        {
            "type": "text",
            "text": "# pexpect (pydoc)\n\n**Summary:** pexpect\n\n## Section Outline\n\n- **NAME** (2 lines)\n- **DESCRIPTION** (12 lines) — 1 subsections\n  - run (50 lines)\n- **PACKAGE CONTENTS** (15 lines)\n- **CLASSES** (7 lines) — 4 subsections\n  - class EOF (78 lines)\n  - class ExceptionPexpect (76 lines)\n  - class TIMEOUT (77 lines)\n  - class spawn (644 lines)\n- **FUNCTIONS** (1 lines) — 6 subsections\n  - run (23 lines)\n  - Examples (59 lines)\n  - runu (2 lines)\n  - spawnu (2 lines)\n  - split_command_line (5 lines)\n  - which (4 lines)\n- **DATA** (3 lines)\n- **VERSION** (2 lines)\n- **FILE** (3 lines)\n\n## Full Content\n\n### NAME\n\npexpect\n\n### DESCRIPTION\n\nPexpect is a Python module for spawning child applications and controlling\nthem automatically. Pexpect can be used for automating interactive applications\nsuch as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup\nscripts for duplicating software package installations on different servers. It\ncan be used for automated software testing. Pexpect is in the spirit of Don\nLibes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python\nrequire TCL and Expect or require C extensions to be compiled. Pexpect does not\nuse C, Expect, or TCL extensions. It should work on any platform that supports\nthe standard Python pty module. The Pexpect interface focuses on ease of use so\nthat simple tasks are easy.\n\nThere are two main interfaces to the Pexpect system; these are the function,\n\n#### run\n\nfunction is simpler than spawn, and is good for quickly calling program. When\nyou call the run() function it executes a given program and then returns the\noutput. This is a handy replacement for os.system().\n\nFor example::\n\npexpect.run('ls -la')\n\nThe spawn class is the more powerful interface to the Pexpect system. You can\nuse this to spawn a child program then interact with it by sending input and\nexpecting responses (waiting for patterns in the child's output).\n\nFor example::\n\nchild = pexpect.spawn('scp foo user@example.com:.')\nchild.expect('Password:')\nchild.sendline(mypassword)\n\nThis works even for commands that ask for passwords or other input outside of\nthe normal stdio streams. For example, ssh reads input directly from the TTY\ndevice which bypasses stdin.\n\nCredits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,\nRobert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids\nvander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,\nJacques-Etienne Baudoux, Geoffrey Marshall, Francisco Lourenco, Glen Mabey,\nKarthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume\nChazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn, John\nSpiegel, Jan Grant, and Shane Kerr. Let me know if I forgot anyone.\n\nPexpect is free, open source, and all that good stuff.\nhttp://pexpect.sourceforge.net/\n\nPEXPECT LICENSE\n\nThis license is approved by the OSI and FSF as GPL-compatible.\nhttp://opensource.org/licenses/isc-license.txt\n\nCopyright (c) 2012, Noah Spurrier <noah@noah.org>\nPERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY\nPURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE\nCOPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n### PACKAGE CONTENTS\n\nANSI\nFSM\nasync\nexceptions\nexpect\nfdpexpect\npopenspawn\nptyspawn\npxssh\nreplwrap\nrun\nscreen\nspawnbase\nutils\n\n### CLASSES\n\nbuiltins.Exception(builtins.BaseException)\npexpect.exceptions.ExceptionPexpect\npexpect.exceptions.EOF\npexpect.exceptions.TIMEOUT\npexpect.spawnbase.SpawnBase(builtins.object)\npexpect.ptyspawn.spawn\n\n#### class EOF\n\n|  EOF(value)\n|\n|  Raised when EOF is read from a child.\n|  This usually means the child has exited.\n|\n|  Method resolution order:\n|      EOF\n|      ExceptionPexpect\n|      builtins.Exception\n|      builtins.BaseException\n|      builtins.object\n|\n|  Methods inherited from ExceptionPexpect:\n|\n|  init(self, value)\n|      Initialize self.  See help(type(self)) for accurate signature.\n|\n|  str(self)\n|      Return str(self).\n|\n|  gettrace(self)\n|      This returns an abbreviated stack trace with lines that only concern\n|      the caller. In other words, the stack trace inside the Pexpect module\n|      is not included.\n|\n|  ----------------------------------------------------------------------\n|  Data descriptors inherited from ExceptionPexpect:\n|\n|  weakref\n|      list of weak references to the object (if defined)\n|\n|  ----------------------------------------------------------------------\n|  Static methods inherited from builtins.Exception:\n|\n|  new(*args, kwargs) from builtins.type\n|      Create and return a new object.  See help(type) for accurate signature.\n|\n|  ----------------------------------------------------------------------\n|  Methods inherited from builtins.BaseException:\n|\n|  delattr(self, name, /)\n|      Implement delattr(self, name).\n|\n|  getattribute(self, name, /)\n|      Return getattr(self, name).\n|\n|  reduce(...)\n|      Helper for pickle.\n|\n|  repr(self, /)\n|      Return repr(self).\n|\n|  setattr(self, name, value, /)\n|      Implement setattr(self, name, value).\n|\n|  setstate(...)\n|\n|  withtraceback(...)\n|      Exception.withtraceback(tb) --\n|      set self.traceback to tb and return self.\n|\n|  ----------------------------------------------------------------------\n|  Data descriptors inherited from builtins.BaseException:\n|\n|  cause\n|      exception cause\n|\n|  context\n|      exception context\n|\n|  dict\n|\n|  suppresscontext\n|\n|  traceback\n|\n|  args\n\n#### class ExceptionPexpect\n\n|  ExceptionPexpect(value)\n|\n|  Base class for all exceptions raised by this module.\n|\n|  Method resolution order:\n|      ExceptionPexpect\n|      builtins.Exception\n|      builtins.BaseException\n|      builtins.object\n|\n|  Methods defined here:\n|\n|  init(self, value)\n|      Initialize self.  See help(type(self)) for accurate signature.\n|\n|  str(self)\n|      Return str(self).\n|\n|  gettrace(self)\n|      This returns an abbreviated stack trace with lines that only concern\n|      the caller. In other words, the stack trace inside the Pexpect module\n|      is not included.\n|\n|  ----------------------------------------------------------------------\n|  Data descriptors defined here:\n|\n|  weakref\n|      list of weak references to the object (if defined)\n|\n|  ----------------------------------------------------------------------\n|  Static methods inherited from builtins.Exception:\n|\n|  new(*args, kwargs) from builtins.type\n|      Create and return a new object.  See help(type) for accurate signature.\n|\n|  ----------------------------------------------------------------------\n|  Methods inherited from builtins.BaseException:\n|\n|  delattr(self, name, /)\n|      Implement delattr(self, name).\n|\n|  getattribute(self, name, /)\n|      Return getattr(self, name).\n|\n|  reduce(...)\n|      Helper for pickle.\n|\n|  repr(self, /)\n|      Return repr(self).\n|\n|  setattr(self, name, value, /)\n|      Implement setattr(self, name, value).\n|\n|  setstate(...)\n|\n|  withtraceback(...)\n|      Exception.withtraceback(tb) --\n|      set self.traceback to tb and return self.\n|\n|  ----------------------------------------------------------------------\n|  Data descriptors inherited from builtins.BaseException:\n|\n|  cause\n|      exception cause\n|\n|  context\n|      exception context\n|\n|  dict\n|\n|  suppresscontext\n|\n|  traceback\n|\n|  args\n\n#### class TIMEOUT\n\n|  TIMEOUT(value)\n|\n|  Raised when a read time exceeds the timeout.\n|\n|  Method resolution order:\n|      TIMEOUT\n|      ExceptionPexpect\n|      builtins.Exception\n|      builtins.BaseException\n|      builtins.object\n|\n|  Methods inherited from ExceptionPexpect:\n|\n|  init(self, value)\n|      Initialize self.  See help(type(self)) for accurate signature.\n|\n|  str(self)\n|      Return str(self).\n|\n|  gettrace(self)\n|      This returns an abbreviated stack trace with lines that only concern\n|      the caller. In other words, the stack trace inside the Pexpect module\n|      is not included.\n|\n|  ----------------------------------------------------------------------\n|  Data descriptors inherited from ExceptionPexpect:\n|\n|  weakref\n|      list of weak references to the object (if defined)\n|\n|  ----------------------------------------------------------------------\n|  Static methods inherited from builtins.Exception:\n|\n|  new(*args, kwargs) from builtins.type\n|      Create and return a new object.  See help(type) for accurate signature.\n|\n|  ----------------------------------------------------------------------\n|  Methods inherited from builtins.BaseException:\n|\n|  delattr(self, name, /)\n|      Implement delattr(self, name).\n|\n|  getattribute(self, name, /)\n|      Return getattr(self, name).\n|\n|  reduce(...)\n|      Helper for pickle.\n|\n|  repr(self, /)\n|      Return repr(self).\n|\n|  setattr(self, name, value, /)\n|      Implement setattr(self, name, value).\n|\n|  setstate(...)\n|\n|  withtraceback(...)\n|      Exception.withtraceback(tb) --\n|      set self.traceback to tb and return self.\n|\n|  ----------------------------------------------------------------------\n|  Data descriptors inherited from builtins.BaseException:\n|\n|  cause\n|      exception cause\n|\n|  context\n|      exception context\n|\n|  dict\n|\n|  suppresscontext\n|\n|  traceback\n|\n|  args\n\n#### class spawn\n\n|  spawn(command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None, ignoresighup=False, echo=True, preexecfn=None, encoding=None, codecerrors='strict', dimensions=None, usepoll=False)\n|\n|  This is the main class interface for Pexpect. Use this class to start\n|  and control child applications.\n|\n|  Method resolution order:\n|      spawn\n|      pexpect.spawnbase.SpawnBase\n|      builtins.object\n|\n|  Methods defined here:\n|\n|  init(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None, ignoresighup=False, echo=True, preexecfn=None, encoding=None, codecerrors='strict', dimensions=None, usepoll=False)\n|      This is the constructor. The command parameter may be a string that\n|      includes a command and any arguments to the command. For example::\n|\n|          child = pexpect.spawn('/usr/bin/ftp')\n|          child = pexpect.spawn('/usr/bin/ssh user@example.com')\n|          child = pexpect.spawn('ls -latr /tmp')\n|\n|      You may also construct it with a list of arguments like so::\n|\n|          child = pexpect.spawn('/usr/bin/ftp', [])\n|          child = pexpect.spawn('/usr/bin/ssh', ['user@example.com'])\n|          child = pexpect.spawn('ls', ['-latr', '/tmp'])\n|\n|      After this the child application will be created and will be ready to\n|      talk to. For normal use, see expect() and send() and sendline().\n|\n|      Remember that Pexpect does NOT interpret shell meta characters such as\n|      redirect, pipe, or wild cards (``>``, ``|``, or ``*``). This is a\n|      common mistake.  If you want to run a command and pipe it through\n|      another command then you must also start a shell. For example::\n|\n|          child = pexpect.spawn('/bin/bash -c \"ls -l | grep LOG > logs.txt\"')\n|          child.expect(pexpect.EOF)\n|\n|      The second form of spawn (where you pass a list of arguments) is useful\n|      in situations where you wish to spawn a command and pass it its own\n|      argument list. This can make syntax more clear. For example, the\n|      following is equivalent to the previous example::\n|\n|          shellcmd = 'ls -l | grep LOG > logs.txt'\n|          child = pexpect.spawn('/bin/bash', ['-c', shellcmd])\n|          child.expect(pexpect.EOF)\n|\n|      The maxread attribute sets the read buffer size. This is maximum number\n|      of bytes that Pexpect will try to read from a TTY at one time. Setting\n|      the maxread size to 1 will turn off buffering. Setting the maxread\n|      value higher may help performance in cases where large amounts of\n|      output are read back from the child. This feature is useful in\n|      conjunction with searchwindowsize.\n|\n|      When the keyword argument *searchwindowsize* is None (default), the\n|      full buffer is searched at each iteration of receiving incoming data.\n|      The default number of bytes scanned at each iteration is very large\n|      and may be reduced to collaterally reduce search cost.  After\n|      :meth:`~.expect` returns, the full buffer attribute remains up to\n|      size *maxread* irrespective of *searchwindowsize* value.\n|\n|      When the keyword argument ``timeout`` is specified as a number,\n|      (default: *30*), then :class:`TIMEOUT` will be raised after the value\n|      specified has elapsed, in seconds, for any of the :meth:`~.expect`\n|      family of method calls.  When None, TIMEOUT will not be raised, and\n|      :meth:`~.expect` may block indefinitely until match.\n|\n|\n|      The logfile member turns on or off logging. All input and output will\n|      be copied to the given file object. Set logfile to None to stop\n|      logging. This is the default. Set logfile to sys.stdout to echo\n|      everything to standard output. The logfile is flushed after each write.\n|\n|      Example log input and output to a file::\n|\n|          child = pexpect.spawn('somecommand')\n|          fout = open('mylog.txt','wb')\n|          child.logfile = fout\n|\n|      Example log to stdout::\n|\n|          # In Python 2:\n|          child = pexpect.spawn('somecommand')\n|          child.logfile = sys.stdout\n|\n|          # In Python 3, we'll use the ``encoding`` argument to decode data\n|          # from the subprocess and handle it as unicode:\n|          child = pexpect.spawn('somecommand', encoding='utf-8')\n|          child.logfile = sys.stdout\n|\n|      The logfileread and logfilesend members can be used to separately log\n|      the input from the child and output sent to the child. Sometimes you\n|      don't want to see everything you write to the child. You only want to\n|      log what the child sends back. For example::\n|\n|          child = pexpect.spawn('somecommand')\n|          child.logfileread = sys.stdout\n|\n|      You will need to pass an encoding to spawn in the above code if you are\n|      using Python 3.\n|\n|      To separately log output sent to the child use logfilesend::\n|\n|          child.logfilesend = fout\n|\n|      If ``ignoresighup`` is True, the child process will ignore SIGHUP\n|      signals. The default is False from Pexpect 4.0, meaning that SIGHUP\n|      will be handled normally by the child.\n|\n|      The delaybeforesend helps overcome a weird behavior that many users\n|      were experiencing. The typical problem was that a user would expect() a\n|      \"Password:\" prompt and then immediately call sendline() to send the\n|      password. The user would then see that their password was echoed back\n|      to them. Passwords don't normally echo. The problem is caused by the\n|      fact that most applications print out the \"Password\" prompt and then\n|      turn off stdin echo, but if you send your password before the\n|      application turned off echo, then you get your password echoed.\n|      Normally this wouldn't be a problem when interacting with a human at a\n|      real keyboard. If you introduce a slight delay just before writing then\n|      this seems to clear up the problem. This was such a common problem for\n|      many users that I decided that the default pexpect behavior should be\n|      to sleep just before writing to the child application. 1/20th of a\n|      second (50 ms) seems to be enough to clear up the problem. You can set\n|      delaybeforesend to None to return to the old behavior.\n|\n|      Note that spawn is clever about finding commands on your path.\n|      It uses the same logic that \"which\" uses to find executables.\n|\n|      If you wish to get the exit status of the child you must call the\n|      close() method. The exit or signal status of the child will be stored\n|      in self.exitstatus or self.signalstatus. If the child exited normally\n|      then exitstatus will store the exit return code and signalstatus will\n|      be None. If the child was terminated abnormally with a signal then\n|      signalstatus will store the signal value and exitstatus will be None::\n|\n|          child = pexpect.spawn('somecommand')\n|          child.close()\n|          print(child.exitstatus, child.signalstatus)\n|\n|      If you need more detail you can also read the self.status member which\n|      stores the status returned by os.waitpid. You can interpret this using\n|      os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.\n|\n|      The echo attribute may be set to False to disable echoing of input.\n|      As a pseudo-terminal, all input echoed by the \"keyboard\" (send()\n|      or sendline()) will be repeated to output.  For many cases, it is\n|      not desirable to have echo enabled, and it may be later disabled\n|      using setecho(False) followed by waitnoecho().  However, for some\n|      platforms such as Solaris, this is not possible, and should be\n|      disabled immediately on spawn.\n|\n|      If preexecfn is given, it will be called in the child process before\n|      launching the given command. This is useful to e.g. reset inherited\n|      signal handlers.\n|\n|      The dimensions attribute specifies the size of the pseudo-terminal as\n|      seen by the subprocess, and is specified as a two-entry tuple (rows,\n|      columns). If this is unspecified, the defaults in ptyprocess will apply.\n|\n|      The usepoll attribute enables using select.poll() over select.select()\n|      for socket handling. This is handy if your system could have > 1024 fds\n|\n|  str(self)\n|      This returns a human-readable string that represents the state of\n|      the object.\n|\n|  close(self, force=True)\n|      This closes the connection with the child application. Note that\n|      calling close() more than once is valid. This emulates standard Python\n|      behavior with files. Set force to True if you want to make sure that\n|      the child is terminated (SIGKILL is sent if the child ignores SIGHUP\n|      and SIGINT).\n|\n|  eof(self)\n|      This returns True if the EOF exception was ever raised.\n|\n|  getecho(self)\n|      This returns the terminal echo mode. This returns True if echo is\n|      on or False if echo is off. Child applications that are expecting you\n|      to enter a password often set ECHO False. See waitnoecho().\n|\n|      Not supported on platforms where ``isatty()`` returns False.\n|\n|  getwinsize(self)\n|      This returns the terminal window size of the child tty. The return\n|      value is a tuple of (rows, cols).\n|\n|  interact(self, escapecharacter='\\x1d', inputfilter=None, outputfilter=None)\n|      This gives control of the child process to the interactive user (the\n|      human at the keyboard). Keystrokes are sent to the child process, and\n|      the stdout and stderr output of the child process is printed. This\n|      simply echos the child stdout and child stderr to the real stdout and\n|      it echos the real stdin to the child stdin. When the user types the\n|      escapecharacter this method will return None. The escapecharacter\n|      will not be transmitted.  The default for escapecharacter is\n|      entered as ``Ctrl - ]``, the very same as BSD telnet. To prevent\n|      escaping, escapecharacter may be set to None.\n|\n|      If a logfile is specified, then the data sent and received from the\n|      child process in interact mode is duplicated to the given log.\n|\n|      You may pass in optional input and output filter functions. These\n|      functions should take bytes array and return bytes array too. Even\n|      with ``encoding='utf-8'`` support, meth:`interact` will always pass\n|      inputfilter and outputfilter bytes. You may need to wrap your\n|      function to decode and encode back to UTF-8.\n|\n|      The outputfilter will be passed all the output from the child process.\n|      The inputfilter will be passed all the keyboard input from the user.\n|      The inputfilter is run BEFORE the check for the escapecharacter.\n|\n|      Note that if you change the window size of the parent the SIGWINCH\n|      signal will not be passed through to the child. If you want the child\n|      window size to change when the parent's window size changes then do\n|      something like the following example::\n|\n|          import pexpect, struct, fcntl, termios, signal, sys\n|          def sigwinchpassthrough (sig, data):\n|              s = struct.pack(\"HHHH\", 0, 0, 0, 0)\n|              a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),\n|                  termios.TIOCGWINSZ , s))\n|              if not p.closed:\n|                  p.setwinsize(a[0],a[1])\n|\n|          # Note this 'p' is global and used in sigwinchpassthrough.\n|          p = pexpect.spawn('/bin/bash')\n|          signal.signal(signal.SIGWINCH, sigwinchpassthrough)\n|          p.interact()\n|\n|  isalive(self)\n|      This tests if the child process is running or not. This is\n|      non-blocking. If the child was terminated then this will read the\n|      exitstatus or signalstatus of the child. This returns True if the child\n|      process appears to be running or False if not. It can take literally\n|      SECONDS for Solaris to return the right status.\n|\n|  isatty(self)\n|      This returns True if the file descriptor is open and connected to a\n|      tty(-like) device, else False.\n|\n|      On SVR4-style platforms implementing streams, such as SunOS and HP-UX,\n|      the child pty may not appear as a terminal device.  This means\n|      methods such as setecho(), setwinsize(), getwinsize() may raise an\n|      IOError.\n|\n|  kill(self, sig)\n|      This sends the given signal to the child application. In keeping\n|      with UNIX tradition it has a misleading name. It does not necessarily\n|      kill the child unless you send the right signal.\n|\n|  readnonblocking(self, size=1, timeout=-1)\n|      This reads at most size characters from the child application. It\n|      includes a timeout. If the read does not complete within the timeout\n|      period then a TIMEOUT exception is raised. If the end of file is read\n|      then an EOF exception will be raised.  If a logfile is specified, a\n|      copy is written to that log.\n|\n|      If timeout is None then the read may block indefinitely.\n|      If timeout is -1 then the self.timeout value is used. If timeout is 0\n|      then the child is polled and if there is no data immediately ready\n|      then this will raise a TIMEOUT exception.\n|\n|      The timeout refers only to the amount of time to read at least one\n|      character. This is not affected by the 'size' parameter, so if you call\n|      readnonblocking(size=100, timeout=30) and only one character is\n|      available right away then one character will be returned immediately.\n|      It will not wait for 30 seconds for another 99 characters to come in.\n|\n|      On the other hand, if there are bytes available to read immediately,\n|      all those bytes will be read (up to the buffer size). So, if the\n|      buffer size is 1 megabyte and there is 1 megabyte of data available\n|      to read, the buffer will be filled, regardless of timeout.\n|\n|      This is a wrapper around os.read(). It uses select.select() or\n|      select.poll() to implement the timeout.\n|\n|  send(self, s)\n|      Sends string ``s`` to the child process, returning the number of\n|      bytes written. If a logfile is specified, a copy is written to that\n|      log.\n|\n|      The default terminal input mode is canonical processing unless set\n|      otherwise by the child process. This allows backspace and other line\n|      processing to be performed prior to transmitting to the receiving\n|      program. As this is buffered, there is a limited size of such buffer.\n|\n|      On Linux systems, this is 4096 (defined by NTTYBUFSIZE). All\n|      other systems honor the POSIX.1 definition PCMAXCANON -- 1024\n|      on OSX, 256 on OpenSolaris, and 1920 on FreeBSD.\n|\n|      This value may be discovered using fpathconf(3)::\n|\n|          >>> from os import fpathconf\n|          >>> print(fpathconf(0, 'PCMAXCANON'))\n|          256\n|\n|      On such a system, only 256 bytes may be received per line. Any\n|      subsequent bytes received will be discarded. BEL (``'\u0007'``) is then\n|      sent to output if IMAXBEL (termios.h) is set by the tty driver.\n|      This is usually enabled by default.  Linux does not honor this as\n|      an option -- it behaves as though it is always set on.\n|\n|      Canonical input processing may be disabled altogether by executing\n|      a shell, then stty(1), before executing the final program::\n|\n|          >>> bash = pexpect.spawn('/bin/bash', echo=False)\n|          >>> bash.sendline('stty -icanon')\n|          >>> bash.sendline('base64')\n|          >>> bash.sendline('x' * 5000)\n|\n|  sendcontrol(self, char)\n|      Helper method that wraps send() with mnemonic access for sending control\n|      character to the child (such as Ctrl-C or Ctrl-D).  For example, to send\n|      Ctrl-G (ASCII 7, bell, '\u0007')::\n|\n|          child.sendcontrol('g')\n|\n|      See also, sendintr() and sendeof().\n|\n|  sendeof(self)\n|      This sends an EOF to the child. This sends a character which causes\n|      the pending parent output buffer to be sent to the waiting child\n|      program without waiting for end-of-line. If it is the first character\n|      of the line, the read() in the user program returns 0, which signifies\n|      end-of-file. This means to work as expected a sendeof() has to be\n|      called at the beginning of a line. This method does not send a newline.\n|      It is the responsibility of the caller to ensure the eof is sent at the\n|      beginning of a line.\n|\n|  sendintr(self)\n|      This sends a SIGINT to the child. It does not require\n|      the SIGINT to be the first character on a line.\n|\n|  sendline(self, s='')\n|      Wraps send(), sending string ``s`` to child process, with\n|      ``os.linesep`` automatically appended. Returns number of bytes\n|      written.  Only a limited number of bytes may be sent for each\n|      line in the default terminal mode, see docstring of :meth:`send`.\n|\n|  setecho(self, state)\n|      This sets the terminal echo mode on or off. Note that anything the\n|      child sent before the echo will be lost, so you should be sure that\n|      your input buffer is empty before you call setecho(). For example, the\n|      following will work as expected::\n|\n|          p = pexpect.spawn('cat') # Echo is on by default.\n|          p.sendline('1234') # We expect see this twice from the child...\n|          p.expect(['1234']) # ... once from the tty echo...\n|          p.expect(['1234']) # ... and again from cat itself.\n|          p.setecho(False) # Turn off tty echo\n|          p.sendline('abcd') # We will set this only once (echoed by cat).\n|          p.sendline('wxyz') # We will set this only once (echoed by cat)\n|          p.expect(['abcd'])\n|          p.expect(['wxyz'])\n|\n|      The following WILL NOT WORK because the lines sent before the setecho\n|      will be lost::\n|\n|          p = pexpect.spawn('cat')\n|          p.sendline('1234')\n|          p.setecho(False) # Turn off tty echo\n|          p.sendline('abcd') # We will set this only once (echoed by cat).\n|          p.sendline('wxyz') # We will set this only once (echoed by cat)\n|          p.expect(['1234'])\n|          p.expect(['1234'])\n|          p.expect(['abcd'])\n|          p.expect(['wxyz'])\n|\n|\n|      Not supported on platforms where ``isatty()`` returns False.\n|\n|  setwinsize(self, rows, cols)\n|      This sets the terminal window size of the child tty. This will cause\n|      a SIGWINCH signal to be sent to the child. This does not change the\n|      physical window size. It changes the size reported to TTY-aware\n|      applications like vi or curses -- applications that respond to the\n|      SIGWINCH signal.\n|\n|  terminate(self, force=False)\n|      This forces a child process to terminate. It starts nicely with\n|      SIGHUP and SIGINT. If \"force\" is True then moves onto SIGKILL. This\n|      returns True if the child was terminated. This returns False if the\n|      child could not be terminated.\n|\n|  wait(self)\n|      This waits until the child exits. This is a blocking call. This will\n|      not read any data from the child, so this will block forever if the\n|      child has unread output and has terminated. In other words, the child\n|      may have printed output then called exit(), but, the child is\n|      technically still alive until its output is read by the parent.\n|\n|      This method is non-blocking if :meth:`wait` has already been called\n|      previously or :meth:`isalive` method returns False.  It simply returns\n|      the previously determined exit status.\n|\n|  waitnoecho(self, timeout=-1)\n|      This waits until the terminal ECHO flag is set False. This returns\n|      True if the echo mode is off. This returns False if the ECHO flag was\n|      not set False before the timeout. This can be used to detect when the\n|      child is waiting for a password. Usually a child application will turn\n|      off echo mode when it is waiting for the user to enter a password. For\n|      example, instead of expecting the \"password:\" prompt you can wait for\n|      the child to set ECHO off::\n|\n|          p = pexpect.spawn('ssh user@example.com')\n|          p.waitnoecho()\n|          p.sendline(mypassword)\n|\n|      If timeout==-1 then this method will use the value in self.timeout.\n|      If timeout==None then this method to block until ECHO flag is False.\n|\n|  write(self, s)\n|      This is similar to send() except that there is no return value.\n|\n|  writelines(self, sequence)\n|      This calls write() for each element in the sequence. The sequence\n|      can be any iterable object producing strings, typically a list of\n|      strings. This does not add line separators. There is no return value.\n|\n|  ----------------------------------------------------------------------\n|  Data descriptors defined here:\n|\n|  flageof\n|\n|  ----------------------------------------------------------------------\n|  Data and other attributes defined here:\n|\n|  usenativeptyfork = True\n|\n|  ----------------------------------------------------------------------\n|  Methods inherited from pexpect.spawnbase.SpawnBase:\n|\n|  enter(self)\n|      # For 'with spawn(...) as child:'\n|\n|  exit(self, etype, evalue, tb)\n|\n|  iter(self)\n|      This is to support iterators over a file-like object.\n|\n|  compilepatternlist(self, patterns)\n|      This compiles a pattern-string or a list of pattern-strings.\n|      Patterns must be a StringType, EOF, TIMEOUT, SREPattern, or a list of\n|      those. Patterns may also be None which results in an empty list (you\n|      might do this if waiting for an EOF or TIMEOUT condition without\n|      expecting any pattern).\n|\n|      This is used by expect() when calling expectlist(). Thus expect() is\n|      nothing more than::\n|\n|           cpl = self.compilepatternlist(pl)\n|           return self.expectlist(cpl, timeout)\n|\n|      If you are using expect() within a loop it may be more\n|      efficient to compile the patterns first and then call expectlist().\n|      This avoid calls in a loop to compilepatternlist()::\n|\n|           cpl = self.compilepatternlist(mypattern)\n|           while somecondition:\n|              ...\n|              i = self.expectlist(cpl, timeout)\n|              ...\n|\n|  expect(self, pattern, timeout=-1, searchwindowsize=-1, async=False, kw)\n|      This seeks through the stream until a pattern is matched. The\n|      pattern is overloaded and may take several types. The pattern can be a\n|      StringType, EOF, a compiled re, or a list of any of those types.\n|      Strings will be compiled to re types. This returns the index into the\n|      pattern list. If the pattern was not a list this returns index 0 on a\n|      successful match. This may raise exceptions for EOF or TIMEOUT. To\n|      avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern\n|      list. That will cause expect to match an EOF or TIMEOUT condition\n|      instead of raising an exception.\n|\n|      If you pass a list of patterns and more than one matches, the first\n|      match in the stream is chosen. If more than one pattern matches at that\n|      point, the leftmost in the pattern list is chosen. For example::\n|\n|          # the input is 'foobar'\n|          index = p.expect(['bar', 'foo', 'foobar'])\n|          # returns 1('foo') even though 'foobar' is a \"better\" match\n|\n|      Please note, however, that buffering can affect this behavior, since\n|      input arrives in unpredictable chunks. For example::\n|\n|          # the input is 'foobar'\n|          index = p.expect(['foobar', 'foo'])\n|          # returns 0('foobar') if all input is available at once,\n|          # but returns 1('foo') if parts of the final 'bar' arrive late\n|\n|      When a match is found for the given pattern, the class instance\n|      attribute *match* becomes an re.MatchObject result.  Should an EOF\n|      or TIMEOUT pattern match, then the match attribute will be an instance\n|      of that exception class.  The pairing before and after class\n|      instance attributes are views of the data preceding and following\n|      the matching pattern.  On general exception, class attribute\n|      *before* is all data received up to the exception, while *match* and\n|      *after* attributes are value None.\n|\n|      When the keyword argument timeout is -1 (default), then TIMEOUT will\n|      raise after the default value specified by the class timeout\n|      attribute. When None, TIMEOUT will not be raised and may block\n|      indefinitely until match.\n|\n|      When the keyword argument searchwindowsize is -1 (default), then the\n|      value specified by the class maxread attribute is used.\n|\n|      A list entry may be EOF or TIMEOUT instead of a string. This will\n|      catch these exceptions and return the index of the list entry instead\n|      of raising the exception. The attribute 'after' will be set to the\n|      exception type. The attribute 'match' will be None. This allows you to\n|      write code like this::\n|\n|              index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])\n|              if index == 0:\n|                  dosomething()\n|              elif index == 1:\n|                  dosomethingelse()\n|              elif index == 2:\n|                  dosomeotherthing()\n|              elif index == 3:\n|                  dosomethingcompletelydifferent()\n|\n|      instead of code like this::\n|\n|              try:\n|                  index = p.expect(['good', 'bad'])\n|                  if index == 0:\n|                      dosomething()\n|                  elif index == 1:\n|                      dosomethingelse()\n|              except EOF:\n|                  dosomeotherthing()\n|              except TIMEOUT:\n|                  dosomethingcompletelydifferent()\n|\n|      These two forms are equivalent. It all depends on what you want. You\n|      can also just expect the EOF if you are waiting for all output of a\n|      child to finish. For example::\n|\n|              p = pexpect.spawn('/bin/ls')\n|              p.expect(pexpect.EOF)\n|              print p.before\n|\n|      If you are trying to optimize for speed then see expectlist().\n|\n|      On Python 3.4, or Python 3.3 with asyncio installed, passing\n|      ``async=True``  will make this return an :mod:`asyncio` coroutine,\n|      which you can yield from to get the same result that this method would\n|      normally give directly. So, inside a coroutine, you can replace this code::\n|\n|          index = p.expect(patterns)\n|\n|      With this non-blocking form::\n|\n|          index = yield from p.expect(patterns, async=True)\n|\n|  expectexact(self, patternlist, timeout=-1, searchwindowsize=-1, async=False, kw)\n|      This is similar to expect(), but uses plain string matching instead\n|      of compiled regular expressions in 'patternlist'. The 'patternlist'\n|      may be a string; a list or other sequence of strings; or TIMEOUT and\n|      EOF.\n|\n|      This call might be faster than expect() for two reasons: string\n|      searching is faster than RE matching and it is possible to limit the\n|      search to just the end of the input buffer.\n|\n|      This method is also useful when you don't want to have to worry about\n|      escaping regular expression characters that you want to match.\n|\n|      Like :meth:`expect`, passing ``async=True`` will make this return an\n|      asyncio coroutine.\n|\n|  expectlist(self, patternlist, timeout=-1, searchwindowsize=-1, async=False, kw)\n|      This takes a list of compiled regular expressions and returns the\n|      index into the patternlist that matched the child output. The list may\n|      also contain EOF or TIMEOUT(which are not compiled regular\n|      expressions). This method is similar to the expect() method except that\n|      expectlist() does not recompile the pattern list on every call. This\n|      may help if you are trying to optimize for speed, otherwise just use\n|      the expect() method.  This is called by expect().\n|\n|\n|      Like :meth:`expect`, passing ``async=True`` will make this return an\n|      asyncio coroutine.\n|\n|  expectloop(self, searcher, timeout=-1, searchwindowsize=-1)\n|      This is the common loop used inside expect. The 'searcher' should be\n|      an instance of searcherre or searcherstring, which describes how and\n|      what to search for in the input.\n|\n|      See expect() for other arguments, return value and exceptions.\n|\n|  fileno(self)\n|      Expose file descriptor for a file-like interface\n|\n|  flush(self)\n|      This does nothing. It is here to support the interface for a\n|      File-like object.\n|\n|  read(self, size=-1)\n|      This reads at most \"size\" bytes from the file (less if the read hits\n|      EOF before obtaining size bytes). If the size argument is negative or\n|      omitted, read all data until EOF is reached. The bytes are returned as\n|      a string object. An empty string is returned when EOF is encountered\n|      immediately.\n|\n|  readline(self, size=-1)\n|      This reads and returns one entire line. The newline at the end of\n|      line is returned as part of the string, unless the file ends without a\n|      newline. An empty string is returned if EOF is encountered immediately.\n|      This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because\n|      this is what the pseudotty device returns. So contrary to what you may\n|      expect you will receive newlines as \\r\\n.\n|\n|      If the size argument is 0 then an empty string is returned. In all\n|      other cases the size argument is ignored, which is not standard\n|      behavior for a file-like object.\n|\n|  readlines(self, sizehint=-1)\n|      This reads until EOF using readline() and returns a list containing\n|      the lines thus read. The optional 'sizehint' argument is ignored.\n|      Remember, because this reads until EOF that means the child\n|      process should have closed its stdout. If you run this method on\n|      a child that is still running with its stdout open then this\n|      method will block until it timesout.\n|\n|  ----------------------------------------------------------------------\n|  Data descriptors inherited from pexpect.spawnbase.SpawnBase:\n|\n|  dict\n|      dictionary for instance variables (if defined)\n|\n|  weakref\n|      list of weak references to the object (if defined)\n|\n|  buffer\n|\n|  ----------------------------------------------------------------------\n|  Data and other attributes inherited from pexpect.spawnbase.SpawnBase:\n|\n|  encoding = None\n|\n|  pid = None\n\n### FUNCTIONS\n\n#### run\n\nThis function runs the given command; waits for it to finish; then\nreturns all output as a string. STDERR is included in output. If the full\npath to the command is not given then the path is searched.\n\nNote that lines are terminated by CR/LF (\\r\\n) combination even on\nUNIX-like systems because this is the standard for pseudottys. If you set\n'withexitstatus' to true, then run will return a tuple of (commandoutput,\nexitstatus). If 'withexitstatus' is false then this returns just\ncommandoutput.\n\nThe run() function can often be used instead of creating a spawn instance.\nFor example, the following code uses spawn::\n\nfrom pexpect import *\nchild = spawn('scp foo user@example.com:.')\nchild.expect('(?i)password')\nchild.sendline(mypassword)\n\nThe previous code can be replace with the following::\n\nfrom pexpect import *\nrun('scp foo user@example.com:.', events={'(?i)password': mypassword})\n\n#### Examples\n\nStart the apache daemon on the local machine::\n\nfrom pexpect import *\nrun(\"/usr/local/apache/bin/apachectl start\")\n\nCheck in a file using SVN::\n\nfrom pexpect import *\nrun(\"svn ci -m 'automatic commit' myfile.py\")\n\nRun a command and capture exit status::\n\nfrom pexpect import *\n(commandoutput, exitstatus) = run('ls -l /bin', withexitstatus=1)\n\nThe following will run SSH and execute 'ls -l' on the remote machine. The\npassword 'secret' will be sent if the '(?i)password' pattern is ever seen::\n\nrun(\"ssh username@machine.example.com 'ls -l'\",\nevents={'(?i)password':'secret\\n'})\n\nThis will start mencoder to rip a video from DVD. This will also display\nprogress ticks every 5 seconds as it runs. For example::\n\nfrom pexpect import *\ndef printticks(d):\nprint d['eventcount'],\nrun(\"mencoder dvd://1 -o video.avi -oac copy -ovc copy\",\nevents={TIMEOUT:printticks}, timeout=5)\n\nThe 'events' argument should be either a dictionary or a tuple list that\ncontains patterns and responses. Whenever one of the patterns is seen\nin the command output, run() will send the associated response string.\nSo, run() in the above example can be also written as:\n\nrun(\"mencoder dvd://1 -o video.avi -oac copy -ovc copy\",\nevents=[(TIMEOUT,printticks)], timeout=5)\n\nUse a tuple list for events if the command output requires a delicate\ncontrol over what pattern should be matched, since the tuple list is passed\nto pexpect() as its pattern list, with the order of patterns preserved.\n\nNote that you should put newlines in your string if Enter is necessary.\n\nLike the example above, the responses may also contain a callback, either\na function or method.  It should accept a dictionary value as an argument.\nThe dictionary contains all the locals from the run() function, so you can\naccess the child spawn object or any other variable defined in run()\n(eventcount, child, and extraargs are the most useful). A callback may\nreturn True to stop the current run process.  Otherwise run() continues\nuntil the next event. A callback may also return a string which will be\nsent to the child. 'extraargs' is not used by directly run(). It provides\na way to pass data to a callback function through run() through the locals\ndictionary passed to a callback.\n\nLike :class:`spawn`, passing *encoding* will make it work with unicode\ninstead of bytes. You can pass *codecerrors* to control how errors in\nencoding and decoding are handled.\n\n#### runu\n\nDeprecated: pass encoding to run() instead.\n\n#### spawnu\n\nDeprecated: pass encoding to spawn() instead.\n\n#### split_command_line\n\nThis splits a command line into a list of arguments. It splits arguments\non spaces, but handles embedded quotes, doublequotes, and escaped\ncharacters. It's impossible to do this with a regular expression, so I\nwrote a little state machine to parse the command line.\n\n#### which\n\nThis takes a given filename; tries to find it in the environment path;\nthen checks if it is executable. This returns the full path to the filename\nif found and executable. Otherwise this returns None.\n\n### DATA\n\nall = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'spawnu', 'r...\nrevision = ''\n\n### VERSION\n\n4.8.0\n\n### FILE\n\n/usr/lib/python3/dist-packages/pexpect/init.py\n\n"
        }
    ],
    "structuredContent": {
        "command": "pexpect",
        "section": "",
        "mode": "pydoc",
        "summary": "pexpect",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 12,
                "subsections": [
                    {
                        "name": "run",
                        "lines": 50
                    }
                ]
            },
            {
                "name": "PACKAGE CONTENTS",
                "lines": 15,
                "subsections": []
            },
            {
                "name": "CLASSES",
                "lines": 7,
                "subsections": [
                    {
                        "name": "class EOF",
                        "lines": 78
                    },
                    {
                        "name": "class ExceptionPexpect",
                        "lines": 76
                    },
                    {
                        "name": "class TIMEOUT",
                        "lines": 77
                    },
                    {
                        "name": "class spawn",
                        "lines": 644
                    }
                ]
            },
            {
                "name": "FUNCTIONS",
                "lines": 1,
                "subsections": [
                    {
                        "name": "run",
                        "lines": 23
                    },
                    {
                        "name": "Examples",
                        "lines": 59
                    },
                    {
                        "name": "runu",
                        "lines": 2
                    },
                    {
                        "name": "spawnu",
                        "lines": 2
                    },
                    {
                        "name": "split_command_line",
                        "lines": 5
                    },
                    {
                        "name": "which",
                        "lines": 4
                    }
                ]
            },
            {
                "name": "DATA",
                "lines": 3,
                "subsections": []
            },
            {
                "name": "VERSION",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "FILE",
                "lines": 3,
                "subsections": []
            }
        ]
    }
}