Python pexpect.popen_spawn.PopenSpawn() Examples

The following are 13 code examples of pexpect.popen_spawn.PopenSpawn(). 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.popen_spawn , or try the search function .
Example #1
Source File: scoutfish.py    From pychess with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, engine=''):
        if not engine:
            engine = './scoutfish'
        self.p = PopenSpawn(engine, timeout=TIME_OUT_SECOND, encoding="utf-8")
        self.wait_ready()
        self.pgn = ''
        self.db = '' 
Example #2
Source File: get_compatibility_data.py    From cloud-opensource-python with Apache License 2.0 6 votes vote down vote up
def run_cloud_sql_proxy(cloud_sql_proxy_path):
    instance_flag = '-instances={}=tcp:{}'.format(
        INSTANCE_CONNECTION_NAME, PORT)
    if cloud_sql_proxy_path is None:
        assert cloud_sql_proxy_path, 'Could not find cloud_sql_proxy path'
    process = popen_spawn.PopenSpawn([cloud_sql_proxy_path, instance_flag])

    try:
        process.expect('Ready for new connection', timeout=5)
        yield
    except pexpect.exceptions.TIMEOUT:
        raise ConnectionError(
            ('Cloud SQL Proxy was unable to start after 5 seconds. Output '
             'of cloud_sql_proxy: \n{}').format(process.before))
    except pexpect.exceptions.EOF:
        raise ConnectionError(
            ('Cloud SQL Proxy exited unexpectedly. Output of '
             'cloud_sql_proxy: \n{}').format(process.before))
    finally:
        process.kill(signal.SIGTERM) 
Example #3
Source File: polysh_tests.py    From polysh with GNU General Public License v2.0 6 votes vote down vote up
def launch_polysh(args, input_data=None):
    args = ['../run.py'] + args
    options, unused_args = parse_cmdline()
    if options.coverage:
        args = ['./coverage.py', '-x', '-p'] + args
    if options.log:
        logfile = open(options.log, 'a', 0o644)
        args += ['--debug']
        print('Launching:', str(args), file=logfile)
    else:
        logfile = None

    if input_data is None:
        child = pexpect.spawn(args[0], args=args[1:],
                              encoding='utf-8', logfile=logfile)
    else:
        child = PopenSpawn(args, encoding='utf-8', logfile=logfile)
        child.send(input_data)
        child.sendeof()
    return child 
Example #4
Source File: delegator.py    From habu with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self, block=True, binary=False, cwd=None):
        """Runs the given command, with or without pexpect functionality enabled."""
        self.blocking = block

        # Use subprocess.
        if self.blocking:
            popen_kwargs = self._default_popen_kwargs.copy()
            popen_kwargs['universal_newlines'] = not binary
            if cwd:
                popen_kwargs['cwd'] = cwd
            s = subprocess.Popen(self._popen_args, **popen_kwargs)
        # Otherwise, use pexpect.
        else:
            pexpect_kwargs = self._default_pexpect_kwargs.copy()
            if binary:
                pexpect_kwargs['encoding'] = None
            if cwd:
                pexpect_kwargs['cwd'] = cwd
            # Enable Python subprocesses to work with expect functionality.
            pexpect_kwargs['env']['PYTHONUNBUFFERED'] = '1'
            s = PopenSpawn(self._popen_args, **pexpect_kwargs)
        self.subprocess = s
        self.was_run = True 
Example #5
Source File: delegator.py    From pipenv with MIT License 5 votes vote down vote up
def _uses_pexpect(self):
        return isinstance(self.subprocess, PopenSpawn) 
Example #6
Source File: delegator.py    From pipenv with MIT License 5 votes vote down vote up
def run(self, block=True, binary=False, cwd=None, env=None):
        """Runs the given command, with or without pexpect functionality enabled."""
        self.blocking = block

        # Use subprocess.
        if self.blocking:
            popen_kwargs = self._default_popen_kwargs.copy()
            del popen_kwargs["stdin"]
            popen_kwargs["universal_newlines"] = not binary
            if cwd:
                popen_kwargs["cwd"] = cwd
            if env:
                popen_kwargs["env"].update(env)
            s = subprocess.Popen(self._popen_args, **popen_kwargs)
        # Otherwise, use pexpect.
        else:
            pexpect_kwargs = self._default_pexpect_kwargs.copy()
            if binary:
                pexpect_kwargs["encoding"] = None
            if cwd:
                pexpect_kwargs["cwd"] = cwd
            if env:
                pexpect_kwargs["env"].update(env)
            # Enable Python subprocesses to work with expect functionality.
            pexpect_kwargs["env"]["PYTHONUNBUFFERED"] = "1"
            s = PopenSpawn(self._popen_args, **pexpect_kwargs)
        self.subprocess = s
        self.was_run = True 
Example #7
Source File: chess_db.py    From pychess with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, engine=''):
        if not engine:
            engine = './parser'
        self.p = PopenSpawn(engine, timeout=TIME_OUT_SECOND, encoding="utf-8")
        self.pgn = ''
        self.db = '' 
Example #8
Source File: pexpect.py    From metakernel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def spawn(command, args=[], timeout=30, maxread=2000,
          searchwindowsize=None, logfile=None, cwd=None, env=None,
          ignore_sighup=True, echo=True, encoding='utf-8', **kwargs):
    '''This is the main entry point for Pexpect. Use this functio to start
    and control child applications.

    See https://github.com/pexpect/pexpect/blob/master/pexpect/pty_spawn.py
    for more information.
    '''
    codec_errors = kwargs.get('codec_errors', kwargs.get('errors', 'strict'))
    if pty is None:
        command = shlex.split(command, posix=os.name == 'posix')
        command += args
        child = PopenSpawn(command, timeout=timeout, maxread=maxread,
                           searchwindowsize=searchwindowsize,
                           logfile=logfile, cwd=cwd, env=env,
                           encoding=encoding, codec_errors=codec_errors)
        child.echo = echo
    else:
        try:
            # Signal handlers are inherited by forked processes, and we can't easily
            # reset it from the subprocess. Since kernelapp ignores SIGINT except in
            # message handlers, we need to temporarily reset the SIGINT handler here
            # so that the child and its children are interruptible.
            try:
                sig = signal.signal(signal.SIGINT, signal.SIG_DFL)
            except ValueError:
                # Only Main Thread can handle signals
                sig = None
            child = pty_spawn(command, args=args, timeout=timeout,
                              maxread=maxread,
                              searchwindowsize=searchwindowsize,
                              logfile=logfile, cwd=cwd, env=env,
                              encoding=encoding, codec_errors=codec_errors)
        finally:
            if sig:
                signal.signal(signal.SIGINT, sig)
    return child


# For backwards compatibility 
Example #9
Source File: delegator.py    From habu with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _uses_pexpect(self):
        return isinstance(self.subprocess, PopenSpawn) 
Example #10
Source File: delegator.py    From delegator.py with MIT License 5 votes vote down vote up
def _uses_pexpect(self):
        return isinstance(self.subprocess, PopenSpawn) 
Example #11
Source File: delegator.py    From delegator.py with MIT License 5 votes vote down vote up
def run(self, block=True, binary=False, cwd=None, env=None):
        """Runs the given command, with or without pexpect functionality enabled."""
        self.blocking = block

        # Use subprocess.
        if self.blocking:
            popen_kwargs = self._default_popen_kwargs.copy()
            del popen_kwargs["stdin"]
            popen_kwargs["universal_newlines"] = not binary
            if cwd:
                popen_kwargs["cwd"] = cwd
            if env:
                popen_kwargs["env"].update(env)
            s = subprocess.Popen(self._popen_args, **popen_kwargs)
        # Otherwise, use pexpect.
        else:
            pexpect_kwargs = self._default_pexpect_kwargs.copy()
            if binary:
                pexpect_kwargs["encoding"] = None
            if cwd:
                pexpect_kwargs["cwd"] = cwd
            if env:
                pexpect_kwargs["env"].update(env)
            # Enable Python subprocesses to work with expect functionality.
            pexpect_kwargs["env"]["PYTHONUNBUFFERED"] = "1"
            s = PopenSpawn(self._popen_args, **pexpect_kwargs)
        self.subprocess = s
        self.was_run = True 
Example #12
Source File: database.py    From django-cloud-deploy with Apache License 2.0 4 votes vote down vote up
def with_cloud_sql_proxy(self,
                             project_id: str,
                             instance_name: str,
                             cloud_sql_proxy_path: Optional[str] = None,
                             region: str = 'us-west1',
                             port: int = 5432):
        """A context manager to run and kill cloud sql proxy subprocesses.

        Used to provides secure access to your Cloud SQL Second Generation
        instances without having to whitelist IP addresses or configure SSL.
        For more information:
        https://cloud.google.com/sql/docs/postgres/sql-proxy

        Args:
            project_id: GCP project id.
            instance_name: Name of the Cloud SQL instance cloud sql proxy
                targets at.
            cloud_sql_proxy_path: The command to run your cloud sql proxy.
            region: Where the Cloud SQL instance is in.
            port: The port your Postgres database is using. By default it is
                5432.

        Yields:
            None

        Raises:
            DatabaseError: If cloud sql proxy failed to start after 5 seconds.
        """
        try:
            db.close_old_connections()
        except django.core.exceptions.ImproperlyConfigured:
            # The Django environment is not correctly setup. This might be
            # because we are calling Django management commands with subprocess
            # calls. In this case the subprocess we are calling will handle
            # closing of old connections.
            pass
        instance_connection_string = '{0}:{1}:{2}'.format(
            project_id, region, instance_name)
        instance_flag = '-instances={}=tcp:{}'.format(
            instance_connection_string, port)
        if cloud_sql_proxy_path is None:
            cloud_sql_proxy_path = shutil.which('cloud_sql_proxy')
            assert cloud_sql_proxy_path, 'could not find cloud_sql_proxy_path'
        process = popen_spawn.PopenSpawn([cloud_sql_proxy_path, instance_flag])
        try:
            # Make sure cloud sql proxy is started before doing the real work
            process.expect('Ready for new connections', timeout=60)
            yield
        except pexpect.exceptions.TIMEOUT:
            raise DatabaseError(
                ('Cloud SQL Proxy was unable to start after 60 seconds. Output '
                 'of cloud_sql_proxy: \n{}').format(process.before))
        except pexpect.exceptions.EOF:
            raise DatabaseError(
                ('Cloud SQL Proxy exited unexpectedly. Output of '
                 'cloud_sql_proxy: \n{}').format(process.before))
        finally:
            process.kill(signal.SIGTERM) 
Example #13
Source File: utils.py    From sos with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def pexpect_run(cmd, shell=False, win_width=None, stdout_socket=None):

    def send_output(output):
        if stdout_socket:
            stdout_socket.send_multipart([
                b'PRINT',
                env.config.get('slave_id', '').encode(),
                output.encode()
            ])
        else:
            sys.stdout.write(output)

    if sys.platform == 'win32':
        import pexpect
        import pexpect.popen_spawn as ps
        child = ps.PopenSpawn(cmd)
        while True:
            try:
                child.expect('\n')
                if env.verbosity > 0:
                    send_output(child.before.decode() + '\n')
            except pexpect.EOF:
                break
        return child.wait()
    else:
        import pexpect
        import subprocess
        if win_width:
            os.environ['COLUMNS'] = str(win_width)
        else:
            os.environ['COLUMNS'] = '80'
        try:
            if isinstance(cmd, str):
                if shell:
                    child = pexpect.spawn(
                        '/bin/bash', ['-c', cmd], timeout=None)
                else:
                    child = pexpect.spawn(cmd, timeout=None)
            else:
                if shell:
                    child = pexpect.spawn(
                        '/bin/bash', ['-c', subprocess.list2cmdline(cmd)],
                        timeout=None)
                else:
                    child = pexpect.spawn(
                        subprocess.list2cmdline(cmd), timeout=None)
            while True:
                try:
                    child.expect('\r\n')
                    if env.verbosity > 0:
                        send_output(child.before.decode() + '\n')
                except pexpect.EOF:
                    break
            child.wait()
            child.close()
            return child.exitstatus
        except Exception as e:
            sys.stderr.write(str(e))
            return 1