Runs a command and returns the exit code, stdout, stderr and possible any extra file.

To get the stderr you have to add "2> file.txt"
10965
protected static function runCommand($cmd, $stderr_file = false, $extra_file = false) {
        $output = [];
        $exitcode = -1;
        exec($cmd, $output, $exitcode);
        return [
            'code' => $exitcode,
            'stdout' => implode("\n", $output),
            'stderr' => $stderr_file ? file_get_contents(stderr_file) : null,
            'extra_file' => $return_file ? file_get_contents($return_file) : null
        ];
    }
66294
def shell_out(cmd, stderr=STDOUT, cwd=None):
    """"""
    if cwd is None:
        from os import getcwd
        cwd = getcwd()  # TODO do I need to normalize this on Windows

    out = check_output(cmd, cwd=cwd, stderr=stderr, universal_newlines=True)
    return _clean_output(out)
578241
def print_err(*args, end='\n'):
    
    print(*args, end=end, file=sys.stderr)
    sys.stderr.flush()
157312
function(command) {
      var t = this;
      t.shellCmd = ChildProcess.exec(command, function(err, stdout, stderr) {
        if (err) {
          var outstr = 'exit';
          if (err.code) {
            outstr += ' (' + err.code + ')';
          }
          if (err.signal) {
            outstr += ' ' + err.signal;
          }
          t._output(outstr);
          return null;
        }
        if (stdout.length) {
          t._output(stdout);
        }
        if (stderr.length) {
          t._output(stderr);
        }
        t.shellCmd = null;
        t._output(CONSOLE_PROMPT);
      });
      return null;
    }
463008
def run_command_orig(cmd):
    
    process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    if process.returncode == 0:
        os.killpg(os.getpgid(pro.pid), signal.SIGTERM)
    else:
        raise BadRCError("Bad rc (%s) for cmd '%s': %s" % (process.returncode, cmd, stdout + stderr))
    return stdout
215358
def run_command(command):
    
    try:
        check_ouput = getattr(
            subprocess, 'check_output', subprocess.check_call)
        result = check_ouput(command, stderr=subprocess.STDOUT, shell=True)
        if check_ouput.__name__ == 'check_output':
            return 0, result
        else:
            return result, None
    except subprocess.CalledProcessError as e:
        return e.returncode, getattr(e, 'output', None)
535846
def _check_cmd(call):
    '''
    
    '''
    if call['retcode'] != 0:
        comment = ''
        std_err = call.get('stderr')
        std_out = call.get('stdout')
        if std_err:
            comment += std_err
        if std_out:
            comment += std_out

        raise CommandExecutionError('Error running command: {0}'.format(comment))

    return call
401905
def run_command(cmd, *args):
    
    command = ' '.join((cmd, args))
    p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()
    return p.retcode, stdout, stderr
721801
def run(command, get_output=False, cwd=None):
    
    if cwd is None:
        cwd = GITPATH

    cprint('===')
    cprint('===  Command: ', command)
    cprint('===  CWD:     ', cwd)
    cprint('===')

    if get_output:
        proc = capture_stdout(command, cwd=cwd)
        out = proc.stdout.read().decode()
        print(out, end='')
        check_exit_code(proc.returncode)
        return out
    else:
        proc = sarge_run(command, cwd=cwd)
        check_exit_code(proc.returncode)
46354
def output(message, opt, extra=None):
    
    print(message, file=sys.stderr)
    if opt.verbose:
        if extra:
            print(extra)

        traceback.print_exc(sys.stderr)
476469
def getExitCode(self, command, env={}, path=None, uid=None, gid=None,
                    usePTY=0, childFDs=None):
        
        deferred = defer.Deferred()
        processProtocol = _SummaryProcessProtocol(deferred)
        self.execute(processProtocol, command, env, path, uid, gid,
                     usePTY, childFDs)
        @deferred.addCallback
        def getStdOut(tuple_):
            _stdout, _stderr, exitCode = tuple_
            return exitCode
        return deferred
129378
def sos_get_command_output(command, timeout=300, stderr=False,
                           chroot=None, chdir=None, env=None,
                           binary=False, sizelimit=None, poller=None):
    
    # Change root or cwd for child only. Exceptions in the prexec_fn
    # closure are caught in the parent (chroot and chdir are bound from
    # the enclosing scope).
    def _child_prep_fn():
        if (chroot):
            os.chroot(chroot)
        if (chdir):
            os.chdir(chdir)

    cmd_env = os.environ.copy()
    # ensure consistent locale for collected command output
    cmd_env['LC_ALL'] = 'C'
    # optionally add an environment change for the command
    if env:
        for key, value in env.items():
            if value:
                cmd_env[key] = value
            else:
                cmd_env.pop(key, None)
    # use /usr/bin/timeout to implement a timeout
    if timeout and is_executable("timeout"):
        command = "timeout %ds %s" % (timeout, command)

    # shlex.split() reacts badly to unicode on older python runtimes.
    if not six.PY3:
        command = command.encode('utf-8', 'ignore')
    args = shlex.split(command)
    # Expand arguments that are wildcard paths.
    expanded_args = []
    for arg in args:
        expanded_arg = glob.glob(arg)
        if expanded_arg:
            expanded_args.extend(expanded_arg)
        else:
            expanded_args.append(arg)
    try:
        p = Popen(expanded_args, shell=False, stdout=PIPE,
                  stderr=STDOUT if stderr else PIPE,
                  bufsize=-1, env=cmd_env, close_fds=True,
                  preexec_fn=_child_prep_fn)

        reader = AsyncReader(p.stdout, sizelimit, binary)
        if poller:
            while reader.running:
                if poller():
                    p.terminate()
                    raise SoSTimeoutError
        stdout = reader.get_contents()
        while p.poll() is None:
            pass

    except OSError as e:
        if e.errno == errno.ENOENT:
            return {'status': 127, 'output': ""}
        else:
            raise e

    if p.returncode == 126 or p.returncode == 127:
        stdout = six.binary_type(b"")

    return {
        'status': p.returncode,
        'output': stdout
    }
844948
def run(args: List[str],
        get_output: bool = False,
        encoding: str = sys.getdefaultencoding()) -> Tuple[str, str]:
    
    printable = " ".join(shlex.quote(x) for x in args).replace("\n", r"\n")
    log.debug("Running external command: {}", printable)
    if get_output:
        p = subprocess.run(args, stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE, check=True)
        stdout, stderr = p.stdout.decode(encoding), p.stderr.decode(encoding)
    else:
        subprocess.check_call(args)
        stdout, stderr = "", ""
    return stdout, stderr
521640
def pipe_commands_to_file(cmds, path, extra_env=None, show_stderr=False):
    
    env = extend_env(extra_env) if extra_env else None
    env_str = (get_env_str(extra_env) + ' ') if extra_env else ''
    cmd_strs = [env_str + ' '.join(cmd) for cmd in cmds]

    logger.info('Saving output of `{0}`'.format(' | '.join(cmd_strs)))

    with open('/dev/null', 'w') as NULL:
        # Start processes
        processes = []
        for cmd_str, cmd in zip(cmd_strs, cmds):
            p_stdin = processes[-1][1].stdout if processes else None
            p_stderr = None if show_stderr else NULL

            p = Popen(cmd, env=env, stdout=PIPE, stdin=p_stdin, stderr=p_stderr)
            processes.append((cmd_str, p))

        p_last = processes[-1][1]

        with open(path, 'wb') as f:
            shutil.copyfileobj(p_last.stdout, f)

            # Close processes
            error = False
            for cmd_str, p in processes:
                p.stdout.close()
                if p.wait() != 0:
                    error = True
            if error:
                raise CalledProcessError(cmd=cmd_str, returncode=p.returncode)
1308452
def run_command(cmd):
    '''
    '''
    output = Popen(cmd,stderr=STDOUT,stdout=PIPE)
    t = output.communicate()[0],output.returncode
    output = {'message':t[0],
              'return_code':t[1]}

    return output
427496
def runCommand(cmd, timeout=None):
    
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = ''

    out, err = p.communicate()
    p.wait(timeout)

    return (out, err)
819029
def succ(cmd, check_stderr=True, stdout=None, stderr=None):
    '''
    
    '''
    code, out, err = run(cmd)

    # Because we're raising error, sometimes we want to process stdout/stderr after catching error
    # so we're copying these outputs if required
    if stdout is not None:
        stdout[:] = out
    if stderr is not None:
        stderr[:] = err

    if code != 0:
        for l in out:
            print(l)
    assert code == 0, 'Return: {} {}\nStderr: {}'.format(code, cmd, err)
    if check_stderr:
        assert err == [], 'Error: {} {}'.format(err, code)
    return code, out, err