Python pexpect.EOF Examples

The following are 30 code examples of pexpect.EOF(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pexpect , or try the search function .
Example #1
Source File: tunnel.py    From Computable with MIT License 8 votes vote down vote up
def _try_passwordless_openssh(server, keyfile):
    """Try passwordless login with shell ssh command."""
    if pexpect is None:
        raise ImportError("pexpect unavailable, use paramiko")
    cmd = 'ssh -f '+ server
    if keyfile:
        cmd += ' -i ' + keyfile
    cmd += ' exit'
    p = pexpect.spawn(cmd)
    while True:
        try:
            p.expect('[Pp]assword:', timeout=.1)
        except pexpect.TIMEOUT:
            continue
        except pexpect.EOF:
            return True
        else:
            return False 
Example #2
Source File: pgn.py    From pychess with GNU General Public License v3.0 6 votes vote down vote up
def init_scoutfish(self):
        """ Create/open .scout database index file to help querying
            using scoutfish from https://github.com/mcostalba/scoutfish
        """
        if scoutfish_path is not None and self.path and self.size > 0:
            try:
                if self.progressbar is not None:
                    from gi.repository import GLib
                    GLib.idle_add(self.progressbar.set_text, _("Creating .scout index file..."))
                self.scoutfish = Scoutfish(engine=(scoutfish_path, ))
                self.scoutfish.open(self.path)
                scout_path = os.path.splitext(self.path)[0] + '.scout'
                if getmtime(self.path) > getmtime(scout_path):
                    self.scoutfish.make()
            except OSError as err:
                self.scoutfish = None
                log.warning("Failed to sart scoutfish. OSError %s %s" % (err.errno, err.strerror))
            except pexpect.TIMEOUT:
                self.scoutfish = None
                log.warning("scoutfish failed (pexpect.TIMEOUT)")
            except pexpect.EOF:
                self.scoutfish = None
                log.warning("scoutfish failed (pexpect.EOF)") 
Example #3
Source File: node.py    From aerospike-admin with Apache License 2.0 6 votes vote down vote up
def _stop_ssh_connection(self, conn):
        if not conn or PEXPECT_VERSION == NO_MODULE:
            return

        if PEXPECT_VERSION == NEW_MODULE:
            conn.logout()
            if conn:
                conn.close()
        elif PEXPECT_VERSION == OLD_MODULE:
            conn.sendline('exit')
            i = conn.expect([pexpect.EOF, "(?i)there are stopped jobs"])
            if i == 1:
                conn.sendline("exit")
                conn.expect(pexpect.EOF)
            if conn:
                conn.close()

        self.remote_system_command_prompt = '[#$] ' 
Example #4
Source File: _pexpect.py    From Computable with MIT License 6 votes vote down vote up
def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):

        """This is similar to expect(), but uses plain string matching instead
        of compiled regular expressions in 'pattern_list'. The 'pattern_list'
        may be a string; a list or other sequence of strings; or TIMEOUT and
        EOF.

        This call might be faster than expect() for two reasons: string
        searching is faster than RE matching and it is possible to limit the
        search to just the end of the input buffer.

        This method is also useful when you don't want to have to worry about
        escaping regular expression characters that you want to match."""

        if isinstance(pattern_list, (bytes, unicode)) or pattern_list in (TIMEOUT, EOF):
            pattern_list = [pattern_list]
        return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize) 
Example #5
Source File: _pexpect.py    From Computable with MIT License 6 votes vote down vote up
def readline(self, size = -1):
        """This reads and returns one entire line. A trailing newline is kept
        in the string, but may be absent when a file ends with an incomplete
        line. Note: This readline() looks for a \\r\\n pair even on UNIX
        because this is what the pseudo tty device returns. So contrary to what
        you may expect you will receive the newline as \\r\\n. An empty string
        is returned when EOF is hit immediately. Currently, the size argument is
        mostly ignored, so this behavior is not standard for a file-like
        object. If size is 0 then an empty string is returned. """

        if size == 0:
            return self._empty_buffer
        index = self.expect ([self._pty_newline, self.delimiter]) # delimiter default is EOF
        if index == 0:
            return self.before + self._pty_newline
        return self.before 
Example #6
Source File: _pexpect.py    From Computable with MIT License 6 votes vote down vote up
def __init__(self, strings):

        """This creates an instance of searcher_string. This argument 'strings'
        may be a list; a sequence of strings; or the EOF or TIMEOUT types. """

        self.eof_index = -1
        self.timeout_index = -1
        self._strings = []
        for n, s in enumerate(strings):
            if s is EOF:
                self.eof_index = n
                continue
            if s is TIMEOUT:
                self.timeout_index = n
                continue
            self._strings.append((n, s)) 
Example #7
Source File: pexpect.py    From smod-1 with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, patterns):

        """This creates an instance that searches for 'patterns' Where
        'patterns' may be a list or other sequence of compiled regular
        expressions, or the EOF or TIMEOUT types."""

        self.eof_index = -1
        self.timeout_index = -1
        self._searches = []
        for n, s in zip(range(len(patterns)), patterns):
            if s is EOF:
                self.eof_index = n
                continue
            if s is TIMEOUT:
                self.timeout_index = n
                continue
            self._searches.append((n, s)) 
Example #8
Source File: pexpect.py    From smod-1 with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, strings):

        """This creates an instance of searcher_string. This argument 'strings'
        may be a list; a sequence of strings; or the EOF or TIMEOUT types. """

        self.eof_index = -1
        self.timeout_index = -1
        self._strings = []
        for n, s in zip(range(len(strings)), strings):
            if s is EOF:
                self.eof_index = n
                continue
            if s is TIMEOUT:
                self.timeout_index = n
                continue
            self._strings.append((n, s)) 
Example #9
Source File: pexpect.py    From smod-1 with GNU General Public License v2.0 6 votes vote down vote up
def expect_exact(self, pattern_list, timeout = -1, searchwindowsize = -1):

        """This is similar to expect(), but uses plain string matching instead
        of compiled regular expressions in 'pattern_list'. The 'pattern_list'
        may be a string; a list or other sequence of strings; or TIMEOUT and
        EOF.

        This call might be faster than expect() for two reasons: string
        searching is faster than RE matching and it is possible to limit the
        search to just the end of the input buffer.

        This method is also useful when you don't want to have to worry about
        escaping regular expression characters that you want to match."""

        if type(pattern_list) in types.StringTypes or pattern_list in (TIMEOUT, EOF):
            pattern_list = [pattern_list]
        return self.expect_loop(searcher_string(pattern_list), timeout, searchwindowsize) 
Example #10
Source File: change_passwd.py    From learning-python with MIT License 6 votes vote down vote up
def change_password2(old_passwd, new_passwd):
    child = pexpect.spawn('passwd')
    i = child.expect(['[Oo]ld [Pp]assword', '.current.*password', '[Nn]ew [Pp]assword'])

    # Root does not require old password, so it gets to bypass the next step.
    if i == 0 or i == 1:
        child.sendline(old_passwd)
        child.expect('[Nn]ew [Pp]assword')

    child.sendline(new_passwd)
    i = child.expect(['[Nn]ew [Pp]assword', '[Rr]etype', '[Rr]e-enter'])

    if i == 0:
        print('Host did not like new password. Here is what it said...')
        print(child.before)
        child.send(chr(3)) # Ctrl-C
        child.sendline('') # This should tell remote passwd command to quit.
        return
    child.sendline(new_passwd)
    child.expect(pexpect.EOF) 
Example #11
Source File: pexpect.py    From smod-1 with GNU General Public License v2.0 6 votes vote down vote up
def readline (self, size = -1):    # File-like object.

        """This reads and returns one entire line. A trailing newline is kept
        in the string, but may be absent when a file ends with an incomplete
        line. Note: This readline() looks for a \\r\\n pair even on UNIX
        because this is what the pseudo tty device returns. So contrary to what
        you may expect you will receive the newline as \\r\\n. An empty string
        is returned when EOF is hit immediately. Currently, the size argument is
        mostly ignored, so this behavior is not standard for a file-like
        object. If size is 0 then an empty string is returned. """

        if size == 0:
            return ''
        index = self.expect (['\r\n', self.delimiter]) # delimiter default is EOF
        if index == 0:
            return self.before + '\r\n'
        else:
            return self.before 
Example #12
Source File: test_forge.py    From forge with Apache License 2.0 6 votes vote down vote up
def do_test_rebuilder(tree, path):
    directory = mktree(FORGE_YAML + tree, MANGLE=MANGLE)
    forge = launch(directory, "forge build containers")
    forge.expect(pexpect.EOF)
    assert forge.wait() == 0
    assert run_image(directory).strip() == "hello"

    with open(os.path.join(directory, path), "write") as f:
        f.write('print("goodbye")\n')

    forge = launch(directory, "forge build containers")
    forge.expect(pexpect.EOF)
    assert forge.wait() == 0
    assert run_image(directory).strip() == "goodbye"

    forge = launch(directory, "forge clean")
    forge.expect("docker kill ")
    forge.expect(pexpect.EOF)
    assert forge.wait() == 0 
Example #13
Source File: dual_proxy_server.py    From universe with MIT License 6 votes vote down vote up
def recv_ClientInit(self, block):
        # start reward proxy.
        self._log_info('Starting reward proxy server')
        self.reward_proxy = pexpect.spawnu(self.factory.reward_proxy_bin,
                                           logfile=sys.stdout,
                                           timeout=None)

        # wait on reward proxy to be up.
        self._log_info('Waiting for reward proxy server')
        self.reward_proxy.expect('\[RewardProxyServer\]')
        self.reward_proxy_thread = threading.Thread(target=lambda: self.reward_proxy.expect(pexpect.EOF))
        self.reward_proxy_thread.start()

        self._log_info('Reward proxy server is up %s', self.reward_proxy.before)

        super(DualProxyServer, self).recv_ClientInit(block)

        self.logfile_dir = self.log_manager.logfile_dir 
Example #14
Source File: delegator.py    From pipenv with MIT License 6 votes vote down vote up
def _pexpect_out(self):
        if self.subprocess.encoding:
            result = ""
        else:
            result = b""

        if self.subprocess.before:
            result += self.subprocess.before

        if self.subprocess.after and self.subprocess.after not in (pexpect.EOF, pexpect.TIMEOUT):
            try:
                result += self.subprocess.after
            except (pexpect.EOF, pexpect.TIMEOUT):
                pass

        result += self.subprocess.read()
        return result 
Example #15
Source File: pgn.py    From pychess with GNU General Public License v3.0 5 votes vote down vote up
def init_chess_db(self):
        """ Create/open polyglot .bin file with extra win/loss/draw stats
            using chess_db parser from https://github.com/mcostalba/chess_db
        """
        if chess_db_path is not None and self.path and self.size > 0:
            try:
                if self.progressbar is not None:
                    from gi.repository import GLib
                    GLib.idle_add(self.progressbar.set_text, _("Creating .bin index file..."))
                self.chess_db = Parser(engine=(chess_db_path, ))
                self.chess_db.open(self.path)
                bin_path = os.path.splitext(self.path)[0] + '.bin'
                if not os.path.isfile(bin_path):
                    log.debug("No valid games found in %s" % self.path)
                    self.chess_db = None
                elif getmtime(self.path) > getmtime(bin_path):
                    self.chess_db.make()
            except OSError as err:
                self.chess_db = None
                log.warning("Failed to sart chess_db parser. OSError %s %s" % (err.errno, err.strerror))
            except pexpect.TIMEOUT:
                self.chess_db = None
                log.warning("chess_db parser failed (pexpect.TIMEOUT)")
            except pexpect.EOF:
                self.chess_db = None
                log.warning("chess_db parser failed (pexpect.EOF)") 
Example #16
Source File: tunnel.py    From pySINDy with MIT License 5 votes vote down vote up
def _try_passwordless_openssh(server, keyfile):
    """Try passwordless login with shell ssh command."""
    if pexpect is None:
        raise ImportError("pexpect unavailable, use paramiko")
    cmd = 'ssh -f '+ server
    if keyfile:
        cmd += ' -i ' + keyfile
    cmd += ' exit'
    
    # pop SSH_ASKPASS from env
    env = os.environ.copy()
    env.pop('SSH_ASKPASS', None)

    ssh_newkey = 'Are you sure you want to continue connecting'
    p = pexpect.spawn(cmd, env=env)
    while True:
        try:
            i = p.expect([ssh_newkey, _password_pat], timeout=.1)
            if i==0:
                raise SSHException('The authenticity of the host can\'t be established.')
        except pexpect.TIMEOUT:
            continue
        except pexpect.EOF:
            return True
        else:
            return False 
Example #17
Source File: stata_session.py    From stata_kernel with GNU General Public License v3.0 5 votes vote down vote up
def _mata_break(self, match_index, child):
        # Only full input allowed in mata: If command ended in line
        # continuation, yell at the user. Note that some valid mata code
        # ends in a line continuation. In this case we hack it by adding
        # {} and {}.
        if self.mata_mode and child.after.startswith('> ') and match_index == 0:
            mata_index = -1
            child.sendline('{}\n')
            while mata_index == -1:
                mata_index = child.expect([
                    r'\r\n\.', r'\r\n:', r'\r\n>', pexpect.EOF])
                sleep(0.01)

            mata_index = -1
            child.sendline('{}\n')
            while mata_index == -1:
                mata_index = child.expect([
                    r'\r\n\.', r'\r\n:', r'\r\n>', pexpect.EOF])
                sleep(0.01)

            res = re.sub(r'^ *{}(\r\n)?', '', child.before)
            self.kernel.send_response(
                self.kernel.iopub_socket, 'stream', {
                    'text': res + '\n',
                    'name': 'stdout'})

            self.mata_restart = True
            if re.match(r'(\r?\n)? *>(\r?\n)?', child.after):
                if config.get('execution_mode') == 'console':
                    child.sendcontrol('c')
                    child.sendcontrol('d')
                    child.sendline('\r\n')
                else:
                    self.automate('UtilSetStataBreak')

                child.expect(r'\r?\n: ') 
Example #18
Source File: __init__.py    From camr with GNU General Public License v2.0 5 votes vote down vote up
def sendeof(self):

        '''This sends an EOF to the child. This sends a character which causes
        the pending parent output buffer to be sent to the waiting child
        program without waiting for end-of-line. If it is the first character
        of the line, the read() in the user program returns 0, which signifies
        end-of-file. This means to work as expected a sendeof() has to be
        called at the beginning of a line. This method does not send a newline.
        It is the responsibility of the caller to ensure the eof is sent at the
        beginning of a line. '''

        self.send(self._chr(self._EOF)) 
Example #19
Source File: pexpect.py    From smod-1 with GNU General Public License v2.0 5 votes vote down vote up
def sendeof(self):

        """This sends an EOF to the child. This sends a character which causes
        the pending parent output buffer to be sent to the waiting child
        program without waiting for end-of-line. If it is the first character
        of the line, the read() in the user program returns 0, which signifies
        end-of-file. This means to work as expected a sendeof() has to be
        called at the beginning of a line. This method does not send a newline.
        It is the responsibility of the caller to ensure the eof is sent at the
        beginning of a line. """

        ### Hmmm... how do I send an EOF?
        ###C  if ((m = write(pty, *buf, p - *buf)) < 0)
        ###C      return (errno == EWOULDBLOCK) ? n : -1;
        #fd = sys.stdin.fileno()
        #old = termios.tcgetattr(fd) # remember current state
        #attr = termios.tcgetattr(fd)
        #attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF
        #try: # use try/finally to ensure state gets restored
        #    termios.tcsetattr(fd, termios.TCSADRAIN, attr)
        #    if hasattr(termios, 'CEOF'):
        #        os.write (self.child_fd, '%c' % termios.CEOF)
        #    else:
        #        # Silly platform does not define CEOF so assume CTRL-D
        #        os.write (self.child_fd, '%c' % 4)
        #finally: # restore state
        #    termios.tcsetattr(fd, termios.TCSADRAIN, old)
        if hasattr(termios, 'VEOF'):
            char = termios.tcgetattr(self.child_fd)[6][termios.VEOF]
        else:
            # platform does not define VEOF so assume CTRL-D
            char = chr(4)
        self.send(char) 
Example #20
Source File: pexpect.py    From smod-1 with GNU General Public License v2.0 5 votes vote down vote up
def readlines (self, sizehint = -1):    # File-like object.

        """This reads until EOF using readline() and returns a list containing
        the lines thus read. The optional "sizehint" argument is ignored. """

        lines = []
        while True:
            line = self.readline()
            if not line:
                break
            lines.append(line)
        return lines 
Example #21
Source File: __init__.py    From camr with GNU General Public License v2.0 5 votes vote down vote up
def eof(self):

        '''This returns True if the EOF exception was ever raised.
        '''

        return self.flag_eof 
Example #22
Source File: __init__.py    From camr with GNU General Public License v2.0 5 votes vote down vote up
def _pattern_type_err(self, pattern):
        raise TypeError('got {badtype} ({badobj!r}) as pattern, must be one'
                        ' of: {goodtypes}, pexpect.EOF, pexpect.TIMEOUT'\
                        .format(badtype=type(pattern),
                                badobj=pattern,
                                goodtypes=', '.join([str(ast)\
                                    for ast in self.allowed_string_types])
                                )
                        ) 
Example #23
Source File: pexpect.py    From smod-1 with GNU General Public License v2.0 5 votes vote down vote up
def read (self, size = -1):   # File-like object.

        """This reads at most "size" bytes from the file (less if the read hits
        EOF before obtaining size bytes). If the size argument is negative or
        omitted, read all data until EOF is reached. The bytes are returned as
        a string object. An empty string is returned when EOF is encountered
        immediately. """

        if size == 0:
            return ''
        if size < 0:
            self.expect (self.delimiter) # delimiter default is EOF
            return self.before

        # I could have done this more directly by not using expect(), but
        # I deliberately decided to couple read() to expect() so that
        # I would catch any bugs early and ensure consistant behavior.
        # It's a little less efficient, but there is less for me to
        # worry about if I have to later modify read() or expect().
        # Note, it's OK if size==-1 in the regex. That just means it
        # will never match anything in which case we stop only on EOF.
        cre = re.compile('.{%d}' % size, re.DOTALL)
        index = self.expect ([cre, self.delimiter]) # delimiter default is EOF
        if index == 0:
            return self.after ### self.before should be ''. Should I assert this?
        return self.before 
Example #24
Source File: hpacucli.py    From hardware with Apache License 2.0 5 votes vote down vote up
def launch(self):
        '''Launch an hpacucli from /usr/sbin.

Must be called before any other method.
'''
        # With the hpsa kernel module, we need to load the sg kernel
        # module before to have everything working. So we always load
        # it.
        os.system('modprobe sg')
        path = None
        for path2 in ('/usr/sbin/ssacli',
                      '/usr/sbin/hpssacli',
                      '/usr/sbin/hpacucli'):
            if os.path.exists(path2):
                path = path2
                break
        if path:
            try:
                if self.debug:
                    print('Launching', path)
                self.process = pexpect.spawn(path, encoding='utf-8')
                self.process.expect(PROMPT_REGEXP)
            except (OSError, pexpect.EOF, pexpect.TIMEOUT):
                return False
            return True

        return False 
Example #25
Source File: pty_spawn.py    From pipenv with MIT License 5 votes vote down vote up
def sendeof(self):
        '''This sends an EOF to the child. This sends a character which causes
        the pending parent output buffer to be sent to the waiting child
        program without waiting for end-of-line. If it is the first character
        of the line, the read() in the user program returns 0, which signifies
        end-of-file. This means to work as expected a sendeof() has to be
        called at the beginning of a line. This method does not send a newline.
        It is the responsibility of the caller to ensure the eof is sent at the
        beginning of a line. '''

        n, byte = self.ptyproc.sendeof()
        self._log_control(byte) 
Example #26
Source File: pxssh.py    From pipenv with MIT License 5 votes vote down vote up
def logout (self):
        '''Sends exit to the remote shell.

        If there are stopped jobs then this automatically sends exit twice.
        '''
        self.sendline("exit")
        index = self.expect([EOF, "(?i)there are stopped jobs"])
        if index==1:
            self.sendline("exit")
            self.expect(EOF)
        self.close() 
Example #27
Source File: __init__.py    From camr with GNU General Public License v2.0 5 votes vote down vote up
def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1):

        '''This is similar to expect(), but uses plain string matching instead
        of compiled regular expressions in 'pattern_list'. The 'pattern_list'
        may be a string; a list or other sequence of strings; or TIMEOUT and
        EOF.

        This call might be faster than expect() for two reasons: string
        searching is faster than RE matching and it is possible to limit the
        search to just the end of the input buffer.

        This method is also useful when you don't want to have to worry about
        escaping regular expression characters that you want to match.'''

        if (isinstance(pattern_list, self.allowed_string_types) or
                pattern_list in (TIMEOUT, EOF)):
            pattern_list = [pattern_list]

        def prepare_pattern(pattern):
            if pattern in (TIMEOUT, EOF):
                return pattern
            if isinstance(pattern, self.allowed_string_types):
                return self._coerce_expect_string(pattern)
            self._pattern_type_err(pattern)

        try:
            pattern_list = iter(pattern_list)
        except TypeError:
            self._pattern_type_err(pattern_list)
        pattern_list = [prepare_pattern(p) for p in pattern_list]
        return self.expect_loop(searcher_string(pattern_list),
                timeout, searchwindowsize) 
Example #28
Source File: _async.py    From pipenv with MIT License 5 votes vote down vote up
def eof_received(self):
        # N.B. If this gets called, async will close the pipe (the spawn object)
        # for us
        try:
            self.expecter.spawn.flag_eof = True
            index = self.expecter.eof()
        except EOF as e:
            self.error(e)
        else:
            self.found(index) 
Example #29
Source File: __init__.py    From camr with GNU General Public License v2.0 5 votes vote down vote up
def __interact_copy(self, escape_character=None,
            input_filter=None, output_filter=None):

        '''This is used by the interact() method.
        '''

        while self.isalive():
            r, w, e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
            if self.child_fd in r:
                try:
                    data = self.__interact_read(self.child_fd)
                except OSError as err:
                    if err.args[0] == errno.EIO:
                        # Linux-style EOF
                        break
                    raise
                if data == b'':
                    # BSD-style EOF
                    break
                if output_filter:
                    data = output_filter(data)
                if self.logfile is not None:
                    self.logfile.write(data)
                    self.logfile.flush()
                os.write(self.STDOUT_FILENO, data)
            if self.STDIN_FILENO in r:
                data = self.__interact_read(self.STDIN_FILENO)
                if input_filter:
                    data = input_filter(data)
                i = data.rfind(escape_character)
                if i != -1:
                    data = data[:i]
                    self.__interact_writen(self.child_fd, data)
                    break
                self.__interact_writen(self.child_fd, data) 
Example #30
Source File: __init__.py    From camr with GNU General Public License v2.0 5 votes vote down vote up
def readlines(self, sizehint=-1):
        '''This reads until EOF using readline() and returns a list containing
        the lines thus read. The optional 'sizehint' argument is ignored.
        Remember, because this reads until EOF that means the child
        process should have closed its stdout. If you run this method on
        a child that is still running with its stdout open then this
        method will block until it timesout.'''

        lines = []
        while True:
            line = self.readline()
            if not line:
                break
            lines.append(line)
        return lines