Run a shell command and return stdout
8693
def execute(cmd):
    """"""
    proc = Popen(cmd, stdout=PIPE)
    stdout, _ = proc.communicate()
    if proc.returncode != 0:
        raise CalledProcessError(proc.returncode, " ".join(cmd))

    return stdout.decode('utf8')
496857
def Shell(device, *command):
    
    if command:
        return device.StreamingShell(' '.join(command))
    else:
        # Retrieve the initial terminal prompt to use as a delimiter for future reads
        terminal_prompt = device.InteractiveShell()
        print(terminal_prompt.decode('utf-8'))

        # Accept user input in a loop and write that into the interactive shells stdin, then print output
        while True:
            cmd = input('> ')
            if not cmd:
                continue
            elif cmd == 'exit':
                break
            else:
                stdout = device.InteractiveShell(cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True)
                if stdout:
                    if isinstance(stdout, bytes):
                        stdout = stdout.decode('utf-8')
                        print(stdout)

        device.Close()
485517
def run(self):
        
        stderr = os.path.abspath(os.path.join(self.outdir, self.name + '.log'))

        if self.pipe:
            self.args += ('|', self.pipe, '2>>'+stderr)

        if self.gzip:
            self.args += ('|', 'gzip', '1>', self.gzip)
        else:
            self.args.append('2>>'+stderr)
            self.args.append('1>>'+stderr)

        # Print timestamp to log

        log = open(stderr, 'a')
        log.write("[gloTK] timestamp={}\n".format(utils.timestamp()))

        cmd = ' '.join(map(str, self.args))
        print(cmd)
        log.write(cmd)

        start = time.time()
        save_cwd = os.getcwd()
        try:
            utils.safe_mkdir(self.outdir)
            os.chdir(self.outdir)
            spawn_pid = os.spawnle(os.P_NOWAIT, self.shell, self.shell, '-c', cmd, self.env)
            wait_pid, retcode, rusage = os.wait4(spawn_pid, 0)
            if wait_pid != spawn_pid:
                utils.die("could not wait for process %d: got %d" % (spawn_pid, wait_pid))
            os.chdir(save_cwd)
        except OSError as e:
            utils.info(e)
            utils.die("could not run wrapper for command:\n%s" % cmd)

        elapsed = time.time() - start
        retcode = os.WEXITSTATUS(retcode)

        if (self.return_ok is not None) and (self.return_ok != retcode):
            # Give some context to the non-zero return.
            if os.path.isfile(stderr):
                subprocess.call(['tail', '-3', stderr])
            utils.die("non-zero return (%d) from command:\n%s" % (retcode, cmd))
        log.close()
1012599
def run(cls, command, cwd=".", **kwargs):
        
        assert isinstance(command, six.string_types)
        command_result = CommandResult()
        command_result.command = command
        use_shell = cls.USE_SHELL
        if "shell" in kwargs:
            use_shell = kwargs.pop("shell")

        # -- BUILD COMMAND ARGS:
        if six.PY2 and isinstance(command, six.text_type):
            # -- PREPARE-FOR: shlex.split()
            # In PY2, shlex.split() requires bytes string (non-unicode).
            # In PY3, shlex.split() accepts unicode string.
            command = codecs.encode(command, "utf-8")
        cmdargs = shlex.split(command)

        # -- TRANSFORM COMMAND (optional)
        command0 = cmdargs[0]
        real_command = cls.COMMAND_MAP.get(command0, None)
        if real_command:
            cmdargs0 = real_command.split()
            cmdargs = cmdargs0 + cmdargs[1:]
        preprocessors = cls.PREPROCESSOR_MAP.get(command0)
        if preprocessors:
            cmdargs = cls.preprocess_command(preprocessors, cmdargs, command, cwd)


        # -- RUN COMMAND:
        try:
            process = subprocess.Popen(cmdargs,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            universal_newlines=True,
                            shell=use_shell,
                            cwd=cwd, **kwargs)
            out, err = process.communicate()
            if six.PY2: # py3: we get unicode strings, py2 not
                default_encoding = 'UTF-8'
                out = six.text_type(out, process.stdout.encoding or default_encoding)
                err = six.text_type(err, process.stderr.encoding or default_encoding)
            process.poll()
            assert process.returncode is not None
            command_result.stdout = out
            command_result.stderr = err
            command_result.returncode = process.returncode
            if cls.DEBUG:
                print("shell.cwd={0}".format(kwargs.get("cwd", None)))
                print("shell.command: {0}".format(" ".join(cmdargs)))
                print("shell.command.output:\n{0};".format(command_result.output))
        except OSError as e:
            command_result.stderr = u"OSError: %s" % e
            command_result.returncode = e.errno
            assert e.errno != 0

        postprocessors = cls.POSTPROCESSOR_MAP.get(command0)
        if postprocessors:
            command_result = cls.postprocess_command(postprocessors, command_result)
        return command_result
669450
def _run(cmd, suppress_errors=False, suppress_output=False):
    
    if is_verbose():
        logger.debug('Executing: "%s"', format(cmd))
    process = subprocess.Popen(
        cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    stderr_log_level = logging.NOTSET if suppress_errors else logging.ERROR
    stdout_log_level = logging.NOTSET if suppress_output else logging.DEBUG

    stdout_thread = PipeReader(
        process.stdout, process, logger, stdout_log_level)
    stderr_thread = PipeReader(
        process.stderr, process, logger, stderr_log_level)

    stdout_thread.start()
    stderr_thread.start()

    while process.poll() is None:
        time.sleep(PROCESS_POLLING_INTERVAL)

    stdout_thread.join()
    stderr_thread.join()

    process.aggr_stdout = stdout_thread.aggr
    process.aggr_stderr = stderr_thread.aggr

    return process
701532
def shell_exec(command):
    """"""
    out = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]
    return out.decode('utf-8')
930399
def execute(self, command):
        '''
        
        '''
        process = Popen(command, stdout=PIPE, stderr=STDOUT, universal_newlines=True)
        while True:
            if process.poll() is not None:
                self.returncode = process.returncode  # pylint: disable=W0201
                break
            yield process.stdout.readline()
603840
def do_shell(self, args):
        """'"""
        if _debug: ConsoleCmd._debug("do_shell %r", args)

        os.system(args)
1372109
def shell_command(cmd, dry_run=False):
    
    if cmd[0] == '/usr/bin/rsync':
        if dry_run:
            cmd = [cmd[0], '-n'] + cmd[1:]
        LOGGER.info('run: %s', ' '.join(cmd))
        subprocess.check_call(cmd)
    else:
        LOGGER.info('run: %s', ' '.join(cmd))
        if not dry_run:
            subprocess.check_call(cmd)
598575
def sh(self, *command, **kwargs):
        """"""
        self.log.debug('shell: %s', ' '.join(command))
        return subprocess.check_call(' '.join(command),
                                     stdout=sys.stdout,
                                     stderr=sys.stderr,
                                     stdin=sys.stdin,
                                     shell=True, **kwargs)
770016
def run(self):
        """"""
        self.logger.debug(f'Running command: {self.cmd}')

        def execute(cmd):
            output = ""
            popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                     universal_newlines=True, shell=True)
            for stdout_line in iter(popen.stdout.readline, ""):
                stdout_line = stdout_line.strip('\n')
                output += stdout_line
                yield stdout_line
            popen.stdout.close()
            return_code = popen.wait()
            if return_code:
                raise subprocess.CalledProcessError(return_code, cmd, output)

        try:
            for out in execute(self.cmd):
                self.logger.info(out)
            return "", 0
        except subprocess.CalledProcessError as e:
            return e.output, e.returncode
458805
def exec_command(self, cmd, tmp_path, sudo_user,sudoable=False, executable='/bin/sh'):
        '''  '''

        ssh_cmd = self._password_cmd()
        ssh_cmd += ["ssh", "-tt", "-q"] + self.common_args + [self.host]

        if not self.runner.sudo or not sudoable:
            if executable:
                ssh_cmd.append(executable + ' -c ' + pipes.quote(cmd))
            else:
                ssh_cmd.append(cmd)
        else:
            sudocmd, prompt = utils.make_sudo_cmd(sudo_user, executable, cmd)
            ssh_cmd.append(sudocmd)

        vvv("EXEC %s" % ssh_cmd, host=self.host)
        try:
            # Make sure stdin is a proper (pseudo) pty to avoid: tcgetattr errors
            import pty
            master, slave = pty.openpty()
            p = subprocess.Popen(ssh_cmd, stdin=slave,
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdin = os.fdopen(master, 'w', 0)
        except:
            p = subprocess.Popen(ssh_cmd, stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdin = p.stdin

        self._send_password()

        if self.runner.sudo and sudoable and self.runner.sudo_pass:
            fcntl.fcntl(p.stdout, fcntl.F_SETFL,
                        fcntl.fcntl(p.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
            sudo_output = ''
            while not sudo_output.endswith(prompt):
                rfd, wfd, efd = select.select([p.stdout], [],
                                              [p.stdout], self.runner.timeout)
                if p.stdout in rfd:
                    chunk = p.stdout.read()
                    if not chunk:
                        raise errors.AnsibleError('ssh connection closed waiting for sudo password prompt')
                    sudo_output += chunk
                else:
                    stdout = p.communicate()
                    raise errors.AnsibleError('ssh connection error waiting for sudo password prompt')
            stdin.write(self.runner.sudo_pass + '\n')
            fcntl.fcntl(p.stdout, fcntl.F_SETFL, fcntl.fcntl(p.stdout, fcntl.F_GETFL) & ~os.O_NONBLOCK)

        # We can't use p.communicate here because the ControlMaster may have stdout open as well
        stdout = ''
        stderr = ''
        while True:
            rfd, wfd, efd = select.select([p.stdout, p.stderr], [], [p.stdout, p.stderr], 1)
            if p.stdout in rfd:
                dat = os.read(p.stdout.fileno(), 9000)
                stdout += dat
                if dat == '':
                    p.wait()
                    break
            elif p.stderr in rfd:
                dat = os.read(p.stderr.fileno(), 9000)
                stderr += dat
                if dat == '':
                    p.wait()
                    break
            elif p.poll() is not None:
                break
        stdin.close() # close stdin after we read from stdout (see also issue #848)

        if p.returncode != 0 and stderr.find('Bad configuration option: ControlPersist') != -1:
            raise errors.AnsibleError('using -c ssh on certain older ssh versions may not support ControlPersist, set ANSIBLE_SSH_ARGS="" (or ansible_ssh_args in the config file) before running again')

        return (p.returncode, '', stdout, stderr)
1208600
def shell_call(self, shellcmd):
        """"""
        return(subprocess.call(self.shellsetup + shellcmd, shell=True))
1367306
def _run_cli_process(cmd, shell=True):
        
        from subprocess import Popen, PIPE

        p = Popen(cmd, shell=shell, stdout=PIPE, stderr=PIPE)
        _stdout, _stderr = p.communicate()
        return _stdout, _stderr, p.returncode
566842
def run_command(*args)
      require 'tempfile'
      out = Tempfile.new('tty-screen')
      result = system(*args, out: out.path, err: File::NULL)
      return if result.nil?
      out.rewind
      out.read
    ensure
      out.close if out
    end
592571
def run(command, **kwargs):
  
  print command
  p = Popen(shlex.split(command), **kwargs)
  p.wait()

  return p.returncode
1316316
def run_command(self, command):
        
        self.display = DISPLAYS["stdout"]
        self.conf["pagesize"] = 0
        self.onecmd(command)