parameters: (self, patterns, callback,
              optional=False,
              sticky=False,
              errorback=None,
              timeout=15,
              position=None,
              preprocess=True)
return_statement: return hash(pattern_obj)
docstring: Watches the stream of output coming from the underlying terminal program
          for *patterns* and if there's a match *callback* will be called like so::
  
              callback(multiplex_instance, matched_string)
  
          .. tip:: You can provide a string instead of a *callback* function as a shortcut if you just want said string written to the child process.
  
          *patterns* can be a string, an :class:`re.RegexObject` (as created by
          :func:`re.compile`), or a iterator of either/or.  Returns a reference
          object that can be used to remove the registered pattern/callback at any
          time using the :meth:`unexpect` method (see below).
  
          .. note::  This function is non-blocking!
  
          .. warning::  The *timeout* value gets compared against the time :meth:`expect` was called to create it.  So don't wait too long if you're planning on using :meth:`await`!
  
          Here's a simple example that changes a user's password::
  
              >>> def write_password(m_instance, matched):
              ...     print("Sending Password... %s patterns remaining." % len(m_instance._patterns))
              ...     m_instance.writeline('somepassword')
              >>> m = Multiplex('passwd someuser') # Assumes running as root :)
              >>> m.expect('(?i)password:', write_password) # Step 1
              >>> m.expect('(?i)password:', write_password) # Step 2
              >>> print(len(m._patterns)) # To show that there's two in the queue
                  2
              >>> m.spawn() # Execute the command
              >>> m.await(10) # This will block for up to 10 seconds waiting for self._patterns to be empty (not counting optional patterns)
              Sending Password... 1 patterns remaining.
              Sending Password... 0 patterns remaining.
              >>> m.isalive()
              False
              >>> # All done!
  
          .. tip:: The :meth:`await` method will automatically call :meth:`spawn` if not :meth:`isalive`.
  
          This would result in the password of 'someuser' being changed to 'somepassword'.  How is the order determined?  Every time :meth:`expect` is called it creates a new :class:`Pattern` using the given parameters and appends it to `self._patterns` (which is a list).  As each :class:`Pattern` is matched its *callback* gets called and the :class:`Pattern` is removed from `self._patterns` (unless *sticky* is `True`).  So even though the patterns and callbacks listed above were identical they will get executed and removed in the order they were created as each respective :class:`Pattern` is matched.
  
          .. note:: Only the first pattern, or patterns marked as *sticky* are checked against the incoming stream.  If the first non-sticky pattern is marked *optional* then the proceeding pattern will be checked (and so on).  All other patterns will sit in `self._patterns` until their predecessors are matched/removed.
  
          Patterns can be removed from `self._patterns` as needed by calling `unexpect(<reference>)`.  Here's an example::
  
              >>> def handle_accepting_ssh_key(m_instance, matched):
              ...     m_instance.writeline(u'yes')
              >>> m = Multiplex('ssh someuser@somehost')
              >>> ref1 = m.expect('(?i)Are you sure.*\(yes/no\)\?', handle_accepting_ssh_key, optional=True)
              >>> def send_password(m_instance, matched):
              ...    m_instance.unexpect(ref1)
              ...    m_instance.writeline('somepassword')
              >>> ref2 = m.expect('(?i)password:', send_password)
              >>> # spawn() and/or await() and do stuff...
  
          The example above would send 'yes' if asked by the SSH program to accept
          the host's public key (which would result in it being automatically
          removed from `self._patterns`).  However, if this condition isn't met
          before send_password() is called, send_password() will use the reference
          object to remove it directly.  This ensures that the pattern won't be
          accidentally matched later on in the program's execution.
  
          .. note:: Even if we didn't match the "Are you sure..." pattern it would still get auto-removed after its timeout was reached.
  
          **About pattern ordering:** The position at which the given pattern will
          be inserted in `self._patterns` can be specified via the
          *position* argument.  The default is to simply append which should be
          appropriate in most cases.
  
          **About Timeouts:** The *timeout* value passed to expect() will be used
          to determine how long to wait before the pattern is removed from
          self._patterns.  When this occurs, *errorback* will be called with
          current Multiplex instance as the only argument.  If *errorback* is None
          (the default) the pattern will simply be discarded with no action taken.
  
          .. note:: If *sticky* is True the *timeout* value will be ignored.
  
          **Notes about the length of what will be matched:**  The entire terminal
          'screen' will be searched every time new output is read from the
          incoming stream.  This means that the number of rows and columns of the
          terminal determines the size of the search.  So if your pattern needs to
          look for something inside of 50 lines of text you need to make sure that
          when you call `spawn` you specify at least `rows = 50`.  Example::
  
              >>> def handle_long_search(m_instance, matched):
              ...     do_stuff(matched)
              >>> m = Multiplex('someCommandWithLotsOfOutput.sh')
              >>> # 'begin', at least one non-newline char, 50 newlines, at least one char, then 'end':
              >>> my_regex = re.compile('begin.+[\\n]{50}.+end', re.MULTILINE)
              >>> ref = m.expect(my_regex, handle_accepting_ssh_key)
              >>> m.spawn(rows=51, cols=150)
              >>> # Call m.read(), m.spawn() or just let an event loop (e.g. Tornado's IOLoop) take care of things...
  
          **About non-printable characters:** If the *postprocess* argument is
          True (the default), patterns will be checked against the current screen as
          output by the terminal emulator.  This means that things like control
          codes and escape sequences will be handled and discarded by the terminal
          emulator and as such won't be available for patterns to be checked
          against.  To get around this limitation you can set *preprocess* to True
          and the pattern will be checked against the incoming stream before it is
          processed by the terminal emulator.  Example::
  
              >>> def handle_xterm_title(m_instance, matched):
              ...     print("Caught title: %s" % matched)
              >>> m = Multiplex('echo -e "\\033]0;Some Title\\007"')
              >>> title_seq_regex = re.compile(r'\\x1b\\][0-2]\;(.*?)(\\x07|\\x1b\\\\)')
              >>> m.expect(title_seq_regex, handle_xterm_title, preprocess=True) # <-- 'preprocess=True'
              >>> m.await()
              Caught title: Some Title
              >>>
  
          **Notes about debugging:** Instead of using `await` to wait for all of your patterns to be matched at once you can make individual calls to `read` to determine if your patterns are being matched in the way that you want.  For example::
  
              >>> def do_stuff(m_instance, matched):
              ...     print("Debug: do_stuff() got %s" % repr(matched))
              ...     # Do stuff here
              >>> m = Multiplex('someLongComplicatedOutput.sh')
              >>> m.expect('some pattern', do_stuff)
              >>> m.expect('some other pattern', do_stuff)
              >>> m.spawn()
              >>> # Instead of calling await() just call one read() at a time...
              >>> print(repr(m.read()))
              ''
              >>> print(repr(m.read())) # Oops, called read() too soon.  Try again:
              'some other pattern'
              >>> # Doh!  Looks like 'some other pattern' comes first.  Let's start over...
              >>> m.unexpect() # Called with no arguments, it empties m._patterns
              >>> m.terminate() # Tip: This will call unexpect() too so the line above really isn't necessary
              >>> m.expect('some other pattern', do_stuff) # This time this one will be first
              >>> m.expect('some pattern', do_stuff)
              >>> m.spawn()
              >>> print(repr(m.read())) # This time I waited a moment :)
              'Debug: do_stuff() got "some other pattern"'
              'some other pattern'
              >>> # Huzzah!  Now let's see if 'some pattern' matches...
              >>> print(repr(m.read()))
              'Debug: do_stuff() got "some pattern"'
              'some pattern'
              >>> # As you can see, calling read() at-will in an interactive interpreter can be very handy.
  
          **About asynchronous use:**  This mechanism is non-blocking (with the exception of `await`) and is meant to be used asynchronously.  This means that if the running program has no output, `read` won't result in any patterns being matched.  So you must be careful about timing *or* you need to ensure that `read` gets called either automatically when there's data to be read (IOLoop, EPoll, select, etc) or at regular intervals via a loop.  Also, if you're not calling `read` at an interval (i.e. you're using a mechanism to detect when there's output to be read before calling it e.g. IOLoop) you need to ensure that `timeout_check` is called regularly anyway or timeouts won't get detected if there's no output from the underlying program.  See the `MultiplexPOSIXIOLoop.read` override for an example of what this means and how to do it.
docstring_summary: Watches the stream of output coming from the underlying terminal program
          for *patterns* and if there's a match *callback* will be called like so::
docstring_tokens: Watches the stream of output coming from the underlying terminal program for * patterns * and if there s a match * callback * will be called like so ::
function: def expect(self, patterns, callback,
              optional=False,
              sticky=False,
              errorback=None,
              timeout=15,
              position=None,
              preprocess=True):
          """
          Watches the stream of output coming from the underlying terminal program
          for *patterns* and if there's a match *callback* will be called like so::
  
              callback(multiplex_instance, matched_string)
  
          .. tip:: You can provide a string instead of a *callback* function as a shortcut if you just want said string written to the child process.
  
          *patterns* can be a string, an :class:`re.RegexObject` (as created by
          :func:`re.compile`), or a iterator of either/or.  Returns a reference
          object that can be used to remove the registered pattern/callback at any
          time using the :meth:`unexpect` method (see below).
  
          .. note::  This function is non-blocking!
  
          .. warning::  The *timeout* value gets compared against the time :meth:`expect` was called to create it.  So don't wait too long if you're planning on using :meth:`await`!
  
          Here's a simple example that changes a user's password::
  
              >>> def write_password(m_instance, matched):
              ...     print("Sending Password... %s patterns remaining." % len(m_instance._patterns))
              ...     m_instance.writeline('somepassword')
              >>> m = Multiplex('passwd someuser') # Assumes running as root :)
              >>> m.expect('(?i)password:', write_password) # Step 1
              >>> m.expect('(?i)password:', write_password) # Step 2
              >>> print(len(m._patterns)) # To show that there's two in the queue
                  2
              >>> m.spawn() # Execute the command
              >>> m.await(10) # This will block for up to 10 seconds waiting for self._patterns to be empty (not counting optional patterns)
              Sending Password... 1 patterns remaining.
              Sending Password... 0 patterns remaining.
              >>> m.isalive()
              False
              >>> # All done!
  
          .. tip:: The :meth:`await` method will automatically call :meth:`spawn` if not :meth:`isalive`.
  
          This would result in the password of 'someuser' being changed to 'somepassword'.  How is the order determined?  Every time :meth:`expect` is called it creates a new :class:`Pattern` using the given parameters and appends it to `self._patterns` (which is a list).  As each :class:`Pattern` is matched its *callback* gets called and the :class:`Pattern` is removed from `self._patterns` (unless *sticky* is `True`).  So even though the patterns and callbacks listed above were identical they will get executed and removed in the order they were created as each respective :class:`Pattern` is matched.
  
          .. note:: Only the first pattern, or patterns marked as *sticky* are checked against the incoming stream.  If the first non-sticky pattern is marked *optional* then the proceeding pattern will be checked (and so on).  All other patterns will sit in `self._patterns` until their predecessors are matched/removed.
  
          Patterns can be removed from `self._patterns` as needed by calling `unexpect(<reference>)`.  Here's an example::
  
              >>> def handle_accepting_ssh_key(m_instance, matched):
              ...     m_instance.writeline(u'yes')
              >>> m = Multiplex('ssh someuser@somehost')
              >>> ref1 = m.expect('(?i)Are you sure.*\(yes/no\)\?', handle_accepting_ssh_key, optional=True)
              >>> def send_password(m_instance, matched):
              ...    m_instance.unexpect(ref1)
              ...    m_instance.writeline('somepassword')
              >>> ref2 = m.expect('(?i)password:', send_password)
              >>> # spawn() and/or await() and do stuff...
  
          The example above would send 'yes' if asked by the SSH program to accept
          the host's public key (which would result in it being automatically
          removed from `self._patterns`).  However, if this condition isn't met
          before send_password() is called, send_password() will use the reference
          object to remove it directly.  This ensures that the pattern won't be
          accidentally matched later on in the program's execution.
  
          .. note:: Even if we didn't match the "Are you sure..." pattern it would still get auto-removed after its timeout was reached.
  
          **About pattern ordering:** The position at which the given pattern will
          be inserted in `self._patterns` can be specified via the
          *position* argument.  The default is to simply append which should be
          appropriate in most cases.
  
          **About Timeouts:** The *timeout* value passed to expect() will be used
          to determine how long to wait before the pattern is removed from
          self._patterns.  When this occurs, *errorback* will be called with
          current Multiplex instance as the only argument.  If *errorback* is None
          (the default) the pattern will simply be discarded with no action taken.
  
          .. note:: If *sticky* is True the *timeout* value will be ignored.
  
          **Notes about the length of what will be matched:**  The entire terminal
          'screen' will be searched every time new output is read from the
          incoming stream.  This means that the number of rows and columns of the
          terminal determines the size of the search.  So if your pattern needs to
          look for something inside of 50 lines of text you need to make sure that
          when you call `spawn` you specify at least `rows = 50`.  Example::
  
              >>> def handle_long_search(m_instance, matched):
              ...     do_stuff(matched)
              >>> m = Multiplex('someCommandWithLotsOfOutput.sh')
              >>> # 'begin', at least one non-newline char, 50 newlines, at least one char, then 'end':
              >>> my_regex = re.compile('begin.+[\\n]{50}.+end', re.MULTILINE)
              >>> ref = m.expect(my_regex, handle_accepting_ssh_key)
              >>> m.spawn(rows=51, cols=150)
              >>> # Call m.read(), m.spawn() or just let an event loop (e.g. Tornado's IOLoop) take care of things...
  
          **About non-printable characters:** If the *postprocess* argument is
          True (the default), patterns will be checked against the current screen as
          output by the terminal emulator.  This means that things like control
          codes and escape sequences will be handled and discarded by the terminal
          emulator and as such won't be available for patterns to be checked
          against.  To get around this limitation you can set *preprocess* to True
          and the pattern will be checked against the incoming stream before it is
          processed by the terminal emulator.  Example::
  
              >>> def handle_xterm_title(m_instance, matched):
              ...     print("Caught title: %s" % matched)
              >>> m = Multiplex('echo -e "\\033]0;Some Title\\007"')
              >>> title_seq_regex = re.compile(r'\\x1b\\][0-2]\;(.*?)(\\x07|\\x1b\\\\)')
              >>> m.expect(title_seq_regex, handle_xterm_title, preprocess=True) # <-- 'preprocess=True'
              >>> m.await()
              Caught title: Some Title
              >>>
  
          **Notes about debugging:** Instead of using `await` to wait for all of your patterns to be matched at once you can make individual calls to `read` to determine if your patterns are being matched in the way that you want.  For example::
  
              >>> def do_stuff(m_instance, matched):
              ...     print("Debug: do_stuff() got %s" % repr(matched))
              ...     # Do stuff here
              >>> m = Multiplex('someLongComplicatedOutput.sh')
              >>> m.expect('some pattern', do_stuff)
              >>> m.expect('some other pattern', do_stuff)
              >>> m.spawn()
              >>> # Instead of calling await() just call one read() at a time...
              >>> print(repr(m.read()))
              ''
              >>> print(repr(m.read())) # Oops, called read() too soon.  Try again:
              'some other pattern'
              >>> # Doh!  Looks like 'some other pattern' comes first.  Let's start over...
              >>> m.unexpect() # Called with no arguments, it empties m._patterns
              >>> m.terminate() # Tip: This will call unexpect() too so the line above really isn't necessary
              >>> m.expect('some other pattern', do_stuff) # This time this one will be first
              >>> m.expect('some pattern', do_stuff)
              >>> m.spawn()
              >>> print(repr(m.read())) # This time I waited a moment :)
              'Debug: do_stuff() got "some other pattern"'
              'some other pattern'
              >>> # Huzzah!  Now let's see if 'some pattern' matches...
              >>> print(repr(m.read()))
              'Debug: do_stuff() got "some pattern"'
              'some pattern'
              >>> # As you can see, calling read() at-will in an interactive interpreter can be very handy.
  
          **About asynchronous use:**  This mechanism is non-blocking (with the exception of `await`) and is meant to be used asynchronously.  This means that if the running program has no output, `read` won't result in any patterns being matched.  So you must be careful about timing *or* you need to ensure that `read` gets called either automatically when there's data to be read (IOLoop, EPoll, select, etc) or at regular intervals via a loop.  Also, if you're not calling `read` at an interval (i.e. you're using a mechanism to detect when there's output to be read before calling it e.g. IOLoop) you need to ensure that `timeout_check` is called regularly anyway or timeouts won't get detected if there's no output from the underlying program.  See the `MultiplexPOSIXIOLoop.read` override for an example of what this means and how to do it.
          """
          # Create the Pattern object before we do anything else
          if isinstance(patterns, (str, unicode)):
              # Convert to a compiled regex (assume MULTILINE and DOTALL for the
              # sanity of the ignorant)
              patterns = re.compile(patterns, re.MULTILINE|re.DOTALL)
          if isinstance(patterns, (tuple, list)):
              # Ensure that all patterns are RegexObjects
              pattern_list = []
              for pattern in patterns:
                  if isinstance(pattern, str):
                      pattern = re.compile(pattern)
                      pattern_list.append(pattern)
                  else:
                      pattern_list.append(pattern)
              patterns = tuple(pattern_list) # No reason to keep it as a list
          # Convert timeout to a timedelta if necessary
          if timeout: # 0 or None mean "wait forever"
              if isinstance(timeout, (str, int, float)):
                  timeout = timedelta(seconds=float(timeout))
              elif not isinstance(timeout, timedelta):
                  raise TypeError(_(
                      "The timeout value must be a string, integer, float, or a "
                      "timedelta object"))
          pattern_obj = Pattern(patterns, callback,
              optional=optional,
              sticky=sticky,
              errorback=errorback,
              preprocess=preprocess,
              timeout=timeout)
          if isinstance(position, int):
              self._patterns.insert(position, pattern_obj)
          else:
              self._patterns.append(pattern_obj)
          return hash(pattern_obj)
function_tokens: def expect ( self , patterns , callback , optional = False , sticky = False , errorback = None , timeout = 15 , position = None , preprocess = True ) : # Create the Pattern object before we do anything else if isinstance ( patterns , ( str , unicode ) ) : # Convert to a compiled regex (assume MULTILINE and DOTALL for the # sanity of the ignorant) patterns = re . compile ( patterns , re . MULTILINE | re . DOTALL ) if isinstance ( patterns , ( tuple , list ) ) : # Ensure that all patterns are RegexObjects pattern_list = [ ] for pattern in patterns : if isinstance ( pattern , str ) : pattern = re . compile ( pattern ) pattern_list . append ( pattern ) else : pattern_list . append ( pattern ) patterns = tuple ( pattern_list ) # No reason to keep it as a list # Convert timeout to a timedelta if necessary if timeout : # 0 or None mean "wait forever" if isinstance ( timeout , ( str , int , float ) ) : timeout = timedelta ( seconds = float ( timeout ) ) elif not isinstance ( timeout , timedelta ) : raise TypeError ( _ ( "The timeout value must be a string, integer, float, or a " "timedelta object" ) ) pattern_obj = Pattern ( patterns , callback , optional = optional , sticky = sticky , errorback = errorback , preprocess = preprocess , timeout = timeout ) if isinstance ( position , int ) : self . _patterns . insert ( position , pattern_obj ) else : self . _patterns . append ( pattern_obj ) return hash ( pattern_obj )