Python pexpect.ExceptionPexpect() Examples

The following are 16 code examples of pexpect.ExceptionPexpect(). 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: RtkController.py    From rtkbase with GNU Affero General Public License v3.0 6 votes vote down vote up
def shutdown(self):

        if self.launched:
            self.semaphore.acquire()

            self.child.kill(signal.SIGUSR2)

            # wait for rtkrcv to shutdown
            try:
                self.child.wait()
            except pexpect.ExceptionPexpect:
                print("Already dead!!")

            if self.child.isalive():
                r = -1
            else:
                r = 1

            self.semaphore.release()
            self.launched = False

            return r

        # already shut down
        return 2 
Example #2
Source File: RtkController.py    From ReachView with GNU General Public License v3.0 6 votes vote down vote up
def shutdown(self):

        if self.launched:
            self.semaphore.acquire()

            self.child.kill(signal.SIGUSR2)

            # wait for rtkrcv to shutdown
            try:
                self.child.wait()
            except pexpect.ExceptionPexpect:
                print("Already dead!!")

            if self.child.isalive():
                r = -1
            else:
                r = 1

            self.semaphore.release()
            self.launched = False

            return r

        # already shut down
        return 2 
Example #3
Source File: OpTestSSH.py    From op-test with Apache License 2.0 6 votes vote down vote up
def close(self):
        self.util.clear_state(self)
        if self.state == ConsoleState.DISCONNECTED:
            return
        try:
            self.pty.send("\r")
            self.pty.send('~.')
            close_rc = self.pty.expect(
                [pexpect.TIMEOUT, pexpect.EOF], timeout=10)
            log.debug("CLOSE Expect Buffer ID={}".format(hex(id(self.pty))))
            rc_child = self.pty.close()
            exitCode = signalstatus = None
            if self.pty.status != -1:  # leaving here for debug
                if os.WIFEXITED(self.pty.status):
                    exitCode = os.WEXITSTATUS(self.pty.status)
                else:
                    signalstatus = os.WTERMSIG(self.pty.status)
            self.state = ConsoleState.DISCONNECTED
        except pexpect.ExceptionPexpect as e:
            self.state = ConsoleState.DISCONNECTED
            raise "SSH Console: failed to close ssh console"
        except Exception as e:
            self.state = ConsoleState.DISCONNECTED
            pass 
Example #4
Source File: OpTestMambo.py    From op-test with Apache License 2.0 6 votes vote down vote up
def close(self):
        self.util.clear_state(self)
        try:
            rc_child = self.pty.close()
            exitCode = signalstatus = None
            if self.pty.status != -1:  # leaving for debug
                if os.WIFEXITED(self.pty.status):
                    exitCode = os.WEXITSTATUS(self.pty.status)
                else:
                    signalstatus = os.WTERMSIG(self.pty.status)
            self.state = ConsoleState.DISCONNECTED
        except pexpect.ExceptionPexpect as e:
            self.state = ConsoleState.DISCONNECTED
            raise "Mambo Console: failed to close console"
        except Exception as e:
            self.state = ConsoleState.DISCONNECTED
            pass
        log.debug("Mambo close -> TERMINATE") 
Example #5
Source File: SerialConsole.py    From op-test with Apache License 2.0 6 votes vote down vote up
def close(self):
        self.util.clear_state(self)
        if self.state == SerialConsoleState.DISCONNECTED:
            return
        try:
            # Hopefully we don't need to do this....
            #self.pty.send("\r")
            #self.pty.send('~.')
            #close_rc = self.pty.expect(
            #    ['Connection to.*closed', pexpect.TIMEOUT, pexpect.EOF], timeout=10)
            #log.debug("CLOSE Expect Buffer ID={}".format(hex(id(self.pty))))
            rc_child = self.pty.close()
            self.state = SerialConsoleState.DISCONNECTED
            exitCode = signalstatus = None
            if self.pty.status != -1:  # leaving for future debug
                if os.WIFEXITED(self.pty.status):
                    exitCode = os.WEXITSTATUS(self.pty.status)
                else:
                    signalstatus = os.WTERMSIG(self.pty.status)
        except pexpect.ExceptionPexpect:
            self.state = SerialConsoleState.DISCONNECTED
            raise OpTestError("Failed to close serial console")
        except Exception as e:
            self.state = SerialConsoleState.DISCONNECTED
            pass 
Example #6
Source File: OpTestQemu.py    From op-test with Apache License 2.0 6 votes vote down vote up
def close(self):
        self.util.clear_state(self)
        try:
            rc_child = self.pty.close()
            exitCode = signalstatus = None
            if self.pty.status != -1:  # leaving for debug
                if os.WIFEXITED(self.pty.status):
                    exitCode = os.WEXITSTATUS(self.pty.status)
                else:
                    signalstatus = os.WTERMSIG(self.pty.status)
            self.state = ConsoleState.DISCONNECTED
        except pexpect.ExceptionPexpect as e:
            self.state = ConsoleState.DISCONNECTED
            raise "Qemu Console: failed to close console"
        except Exception as e:
            self.state = ConsoleState.DISCONNECTED
            pass
        log.debug("Qemu close -> TERMINATE") 
Example #7
Source File: OpTestHMC.py    From op-test with Apache License 2.0 6 votes vote down vote up
def close(self):
        self.util.clear_state(self)
        try:
            self.pty.close()
            if self.pty.status != -1:  # leaving for debug
                if os.WIFEXITED(self.pty.status):
                    os.WEXITSTATUS(self.pty.status)
                else:
                    os.WTERMSIG(self.pty.status)
            self.state = ConsoleState.DISCONNECTED
        except pexpect.ExceptionPexpect:
            self.state = ConsoleState.DISCONNECTED
            raise "HMC Console: failed to close console"
        except Exception:
            self.state = ConsoleState.DISCONNECTED
        log.debug("HMC close -> TERMINATE") 
Example #8
Source File: Str2StrController.py    From rtkbase with GNU Affero General Public License v3.0 5 votes vote down vote up
def stop(self):
        # terminate the stream

        if self.started:
            self.child.kill(signal.SIGUSR2)
            try:
                self.child.wait()
            except pexpect.ExceptionPexpect:
                print("Str2str already down")

            self.started = False
            return 1

        # str2str already stopped
        return 2 
Example #9
Source File: winpexpect.py    From camr with GNU General Public License v2.0 5 votes vote down vote up
def kill(self, signo):
        """Send a signal to the child (not available on Windows)."""
        raise ExceptionPexpect, 'Signals are not availalbe on Windows' 
Example #10
Source File: fdpexpect.py    From camr with GNU General Public License v2.0 5 votes vote down vote up
def __init__ (self, fd, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None):

        '''This takes a file descriptor (an int) or an object that support the
        fileno() method (returning an int). All Python file-like objects
        support fileno(). '''

        ### TODO: Add better handling of trying to use fdspawn in place of spawn
        ### TODO: (overload to allow fdspawn to also handle commands as spawn does.

        if type(fd) != type(0) and hasattr(fd, 'fileno'):
            fd = fd.fileno()

        if type(fd) != type(0):
            raise ExceptionPexpect('The fd argument is not an int. If this is a command string then maybe you want to use pexpect.spawn.')

        try: # make sure fd is a valid file descriptor
            os.fstat(fd)
        except OSError:
            raise ExceptionPexpect('The fd argument is not a valid file descriptor.')

        self.args = None
        self.command = None
        spawn.__init__(self, None, args, timeout, maxread, searchwindowsize, logfile)
        self.child_fd = fd
        self.own_fd = False
        self.closed = False
        self.name = '<file descriptor %d>' % fd 
Example #11
Source File: fdpexpect.py    From camr with GNU General Public License v2.0 5 votes vote down vote up
def terminate (self, force=False):  # pragma: no cover
        raise ExceptionPexpect('This method is not valid for file descriptors.') 
Example #12
Source File: Str2StrController.py    From ReachView with GNU General Public License v3.0 5 votes vote down vote up
def stop(self):
        # terminate the stream

        if self.started:
            self.child.kill(signal.SIGUSR2)
            try:
                self.child.wait()
            except pexpect.ExceptionPexpect:
                print("Str2str already down")

            self.started = False
            return 1

        # str2str already stopped
        return 2 
Example #13
Source File: application_runner.py    From ros-bridge with MIT License 5 votes vote down vote up
def start_and_run(self, cmdline, env, cwd, shutdown_requested_event, ready_string,  # pylint: disable=too-many-arguments
                      status_updated_fct, log_fct):
        """
        thread function
        """
        status_updated_fct(ApplicationStatus.STARTING)
        try:
            process = self.start_process(cmdline, log_fct, env=env, cwd=cwd)
            self.run(process, shutdown_requested_event, ready_string, status_updated_fct, log_fct)
        except (KeyError, pexpect.ExceptionPexpect) as e:
            self._log_fct("Error while starting process: {}".format(e))
            status_updated_fct(ApplicationStatus.ERROR) 
Example #14
Source File: testHmy.py    From harmony-ops with MIT License 4 votes vote down vote up
def test_keys_mnemonics():
    with open('testHmyReferences/sdkMnemonics.json') as f:
        sdk_mnemonics = json.load(f)
        if not sdk_mnemonics:
            log("Could not load reference data.")
            return False

    passed = True
    for test in sdk_mnemonics["data"]:
        index = test["index"]
        if index != 0:  # CLI currently uses a hardcoded index of 0.
            continue

        mnemonic = test["phrase"]
        correct_address = test["addr"]
        address_name = f'testHmyAcc_{random.randint(0,1e9)}'
        while address_name in ADDRESSES:
            address_name = f'testHmyAcc_{random.randint(0,1e9)}'

        try:
            hmy = pexpect.spawn('./hmy', ['keys', 'add', address_name, '--recover', '--passphrase'], env=ENVIRONMENT)
            hmy.expect("Enter passphrase\r\n")
            hmy.sendline("")
            hmy.expect("Repeat the passphrase:\r\n")
            hmy.sendline("")
            hmy.expect("Enter mnemonic to recover keys from\r\n")
            hmy.sendline(mnemonic)
            hmy.wait()
            hmy.expect(pexpect.EOF)
        except pexpect.ExceptionPexpect as e:
            log(f"Exception occurred when adding a key with mnemonic."
                f"\nException: {e}")
            passed = False

        hmy_address = get_address_from_name(address_name)
        if hmy_address != correct_address or hmy_address is None:
            log(f"Address does not match sdk's address. \n"
                f"\tMnemonic: {mnemonic}\n"
                f"\tCorrect address: {correct_address}\n"
                f"\tCLI address: {hmy_address}")
            passed = False
        else:
            KEYS_ADDED.add(address_name)
    log("Passed", error=False) if passed else log("FAILED", error=False)
    return passed 
Example #15
Source File: ios.py    From ldpush with Apache License 2.0 4 votes vote down vote up
def _DeleteFile(self, file_name):
    """Delete a file.

    Args:
      file_name: A string, the file name.

    Raises:
      DeleteFileError, if the deletion failed.
    """
    try:
      self._connection.child.send('\r')
      self._connection.child.expect('\r\n', timeout=self.timeout_act_user)
      self._connection.child.expect(self._connection.re_prompt,
                                    timeout=self.timeout_act_user,
                                    searchwindowsize=128)
      self._connection.child.send('delete %s\r' % file_name)
    except pexpect.ExceptionPexpect:
      raise DeleteFileError('DeleteFile operation failed. %s' %
                            self._connection.child)

    try:
      pindex = self._connection.child.expect(
          [r'Delete filename \[.*\]\?',
           r'%.*Error.*'],
          timeout=self.timeout_act_user)
      if pindex == 0:
        self._connection.child.send('\r')
        logging.debug('DeleteFile: answering first confirmation.')
        self._connection.child.expect([r'Delete .*\[confirm\]'],
                                      timeout=self.timeout_act_user)
        logging.debug('DeleteFile: answering second confirmation.')
        self._connection.child.send('\r')
      elif pindex == 1:
        raise DeleteFileError('DeleteFile operation failed. %s' %
                              self._connection.child.match)

      pindex = self._connection.child.expect([self._connection.re_prompt,
                                              r'%.*Error.*'],
                                             timeout=self.timeout_act_user)
      if pindex == 1:
        raise DeleteFileError('DeleteFile operation failed. %s' %
                              self._connection.child.match)
      logging.debug('DeleteFile: success.')
    except pexpect.ExceptionPexpect:
      raise DeleteFileError('DeleteFile operation failed. %s' %
                            self._connection.child) 
Example #16
Source File: asa.py    From ldpush with Apache License 2.0 4 votes vote down vote up
def _DeleteFile(self, file_name):
    """Delete a file.

    Args:
      file_name: A string, the file name.

    Raises:
      DeleteFileError, if the deletion failed.
    """
    try:
      self._connection.child.send('\r')
      self._connection.child.expect('\r\n', timeout=self.timeout_act_user)
      self._connection.child.expect(self._connection.re_prompt,
                                    timeout=self.timeout_act_user,
                                    searchwindowsize=128)
      self._connection.child.send('delete %s\r' % file_name)
    except pexpect.ExceptionPexpect:
      raise DeleteFileError('DeleteFile operation failed. %s' %
                            self._connection.child)

    try:
      pindex = self._connection.child.expect(
          [r'Delete filename \[.*\]\?',
           r'%.*Error.*'],
          timeout=self.timeout_act_user)
      if pindex == 0:
        self._connection.child.send('\r')
        logging.debug('DeleteFile: answering first confirmation.')
        self._connection.child.expect([r'Delete .*\[confirm\]'],
                                      timeout=self.timeout_act_user)
        logging.debug('DeleteFile: answering second confirmation.')
        self._connection.child.send('\r')
      elif pindex == 1:
        raise DeleteFileError('DeleteFile operation failed. %s' %
                              self._connection.child.match)

      pindex = self._connection.child.expect([self._connection.re_prompt,
                                              r'%.*Error.*'],
                                             timeout=self.timeout_act_user)
      if pindex == 1:
        raise DeleteFileError('DeleteFile operation failed. %s' %
                              self._connection.child.match)
      logging.debug('DeleteFile: success.')
    except pexpect.ExceptionPexpect:
      raise DeleteFileError('DeleteFile operation failed. %s' %
                            self._connection.child)