Executes a subprocess

    :param params:
        A list of the executable and arguments to pass to it

    :param cwd:
        The working directory to execute the command in

    :return:
        A 2-element tuple of (stdout, stderr)
19095
def _execute(params, cwd):
    

    proc = subprocess.Popen(
        params,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        cwd=cwd
    )
    stdout, stderr = proc.communicate()
    code = proc.wait()
    if code != 0:
        e = OSError('subprocess exit code for %r was %d: %s' % (params, code, stderr))
        e.stdout = stdout
        e.stderr = stderr
        raise e
    return (stdout, stderr)
20549
def _run(self, stdout=subprocess.PIPE):
        '''
        
        '''
        assert self._pop is None
        if self._input is not None:
            self._input._run()

        cwd = (self._cwd if self._cwd else os.getcwd()) + '/'

        def glob_or(expr):
            res = [expr]
            if self._expand and ('*' in expr or '?' in expr):
                if expr and expr[0] != '/':
                    expr = cwd + expr
                res = glob.glob(expr)
                if not res:
                    res = [expr]
            return res

        args = [glob_or(arg) for arg in self._args]
        stderr = subprocess.STDOUT if self._err_to_out else None
        assert not self._stdin or self._input is None, "*** ERROR: Stdin must be none outside of head of chain."
        stdin = self._stdin if self._input is None else self._input._pop.stdout
        if stdin is not None and getattr(stdin, 'fileno', None) is None:
            stdin = subprocess.PIPE
        cmd = [self._cmd] + list(itertools.chain.from_iterable(args))
        if self.debug:
            print "*** DEBUG: Run", cmd
        try:
            self._pop = subprocess.Popen(cmd, stdin=stdin, stdout=stdout, stderr=stderr,
                                         close_fds=True, cwd=self._cwd, env=self._env)
            if stdin == subprocess.PIPE:
                try:
                    # TODO: Write a non-blocking reader-writer to ship data here
                    self._pop.stdin.write(self._stdin.read())
                except AttributeError:
                    self._pop.stdin.write(self._stdin)
        except OSError:
            print "*** ERROR: %r failed at %r" % (self, self._original_cmd)
            raise
670769
def cc_run (args):
    
    prog = b"int main(){}\n"
    pipe = subprocess.Popen(args,
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
    pipe.communicate(input=prog)
    if os.WIFEXITED(pipe.returncode):
        return os.WEXITSTATUS(pipe.returncode) == 0
    return False
576593
def runCommand(cmd, timeout=None, window=None):
    
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = ''
    for line in p.stdout:
        line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backslashreplace').rstrip()
        output += line
        print(line)
        window.Refresh() if window else None        # yes, a 1-line if, so shoot me

    retval = p.wait(timeout)
    return (retval, output)
545995
def run(cmds, **kwargs):
    
    proc = sp.Popen(cmds, bufsize=-1, stdout=sp.PIPE, stderr=sp.STDOUT,
                    close_fds=sys.platform != 'win32')
    for line in proc.stdout:
        print(line[:-1].decode())
    retcode = proc.wait()
    if retcode:
        raise sp.CalledProcessError(retcode, cmds)
453268
function forkProc(cwd, cmd, args, cb) {
    var env = process.env
    if (typeof(cwd) === 'object') {
      cb = cmd
      var cmd = cwd.cmd
      var args = cwd.args
      // Merge/override any variables
      mergeObj(cwd.env, env)
      cwd = cwd.cwd
    }
    if (typeof(cmd) === 'string' && typeof(args) === 'function') {
      var split = cmd.split(/\s+/)
      cmd = split[0]
      cb = args
      args = split.slice(1)
    }
    var proc = spawn(cmd, args, {cwd: cwd, env: env})

    // per-process output buffers
    proc.stderrBuffer = ""
    proc.stdoutBuffer = ""
    proc.stdmergedBuffer = ""

    proc.stdout.setEncoding('utf8')
    proc.stderr.setEncoding('utf8')

    proc.stdout.on('data', function(buf) {
      proc.stdoutBuffer += buf
      proc.stdmergedBuffer += buf
      stdoutBuffer += buf
      stdmergedBuffer += buf
      updateStatus("deployUpdate" , {stdout:buf})
    })

    proc.stderr.on('data', function(buf) {
      proc.stderrBuffer += buf
      proc.stdmergedBuffer += buf
      stderrBuffer += buf
      stdmergedBuffer += buf
      updateStatus("deployUpdate", {stderr:buf})
    })

    proc.on('close', function(exitCode) {
      cb(exitCode)
    })

    return proc
  }
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)
1046965
def do_windowed(self, arg):
        
        if self.cmdprefix:
            raise CmdError("prefix not allowed")
        cmdline = self.input_command_line(arg)
        try:
            process = self.debug.execl(arg,
                                                bConsole = False,
                                                 bFollow = self.options.follow)
            print("Spawned process (%d)" % process.get_pid())
        except Exception:
            raise CmdError("can't execute")
        self.set_fake_last_event(process)
591907
def runCommandReturnOutput(cmd):
    
    splits = shlex.split(cmd)
    proc = subprocess.Popen(
        splits, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    if proc.returncode != 0:
        raise subprocess.CalledProcessError(stdout, stderr)
    return stdout, stderr
958775
def execute_command_in_dir(command, directory, verbose=DEFAULTS['v'], 
                           prefix="Output: ", env=None):
    
    """"""
    
    if os.name == 'nt':
        directory = os.path.normpath(directory)
        
    print_comment("Executing: (%s) in directory: %s" % (command, directory),
                  verbose)
    if env is not None:
        print_comment("Extra env variables %s" % (env), verbose)
    
    try:
        if os.name == 'nt':
            return_string = subprocess.check_output(command, 
                                                    cwd=directory, 
                                                    shell=True, 
                                                    env=env,
                                                    close_fds=False)
        else:
            return_string = subprocess.check_output(command, 
                                                    cwd=directory, 
                                                    shell=True, 
                                                    stderr=subprocess.STDOUT,
                                                    env=env,
                                                    close_fds=True)
        
        return_string = return_string.decode("utf-8") # For Python 3
                                
        print_comment('Command completed. Output: \n %s%s' % \
                      (prefix,return_string.replace('\n','\n '+prefix)), 
                      verbose)

        return return_string
    
    except AttributeError:
        # For python 2.6...
        print_comment_v('Assuming Python 2.6...')
        
        return_string = subprocess.Popen(command, 
                                         cwd=directory, 
                                         shell=True,
                                         stdout=subprocess.PIPE).communicate()[0]
        return return_string
    
    except subprocess.CalledProcessError as e:        
        
        print_comment_v('*** Problem running command: \n       %s'%e)
        print_comment_v('%s%s'%(prefix,e.output.decode().replace('\n','\n'+prefix)))
        
        return None
        
    except:
        print_comment_v('*** Unknown problem running command: %s'%e)
        
        return None
        
    print_comment("Finished execution", verbose)
921261
def run_commands(commands,  # type: List[Union[str, List[str], Dict[str, Union[str, List[str]]]]]
                 directory,  # type: str
                 env=None  # type: Optional[Dict[str, Union[str, int]]]
                ):  # noqa
    # type: (...) -> None
    """"""
    if env is None:
        env = os.environ.copy()
    for step in commands:
        if isinstance(step, (list, six.string_types)):
            execution_dir = directory
            raw_command = step
        elif step.get('command'):  # dictionary
            execution_dir = os.path.join(directory,
                                         step.get('cwd')) if step.get('cwd') else directory  # noqa pylint: disable=line-too-long
            raw_command = step['command']
        else:
            raise AttributeError("Invalid command step: %s" % step)
        command_list = raw_command.split(' ') if isinstance(raw_command, six.string_types) else raw_command  # noqa pylint: disable=line-too-long
        if platform.system().lower() == 'windows':
            command_list = fix_windows_command_list(command_list)

        with change_dir(execution_dir):
            check_call(command_list, env=env)
774660
def ExecuteCmd(cmd, quiet=False):
  
  result = None
  if quiet:
    with open(os.devnull, "w") as fnull:
      result = subprocess.call(cmd, shell=True, stdout=fnull, stderr=fnull)
  else:
    result = subprocess.call(cmd, shell=True)
  return result
174181
def _execute(self, *args: str, **kwargs) -> tuple:
        ''''''
        process = self.execute(
            args=args, options=merge_dict(self.options, kwargs))
        command = ' '.join(process.args)
        if self._dev:
            output, error = process.communicate()
            print(
                "Debug Information",
                "Command: {!r}".format(command),
                "Output: {!r}".format(output.encode('utf-8')),
                "Error: {!r}".format(error.encode('utf-8')),
                sep='\n', end='\n{}\n'.format('=' * 80)
            )
        return process.communicate()
282643
def run_cmd(cmd, input=None, timeout=30, max_try=3, num_try=1):
    '''
    '''
    if type(cmd) == str:
        cmd = cmd.split()
    process = subprocess.Popen(cmd,
                               stdin=open('/dev/null', 'r'),
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    communicate_has_timeout = func_has_arg(func=process.communicate,
                                           arg='timeout')
    exception = Exception
    if communicate_has_timeout:
        exception = subprocess.TimeoutExpired  # python 3.x
    stdout = stderr = b''
    exitcode = None
    try:
        if communicate_has_timeout:
            # python 3.x
            stdout, stderr = process.communicate(input, timeout)
            exitcode = process.wait()
        else:
            # python 2.x
            if timeout is None:
                stdout, stderr = process.communicate(input)
                exitcode = process.wait()
            else:
                # thread-recipe: https://stackoverflow.com/a/4825933
                def target():
                    # closure-recipe: https://stackoverflow.com/a/23558809
                    target.out, target.err = process.communicate(input)
                import threading
                thread = threading.Thread(target=target)
                thread.start()
                thread.join(timeout)
                if thread.is_alive():
                    process.terminate()
                    thread.join()
                    exitcode = None
                else:
                    exitcode = process.wait()
                stdout = target.out
                stderr = target.err
    except exception:
        if num_try < max_try:
            return run_cmd(cmd, input, timeout, max_try, num_try+1)
        else:
            return CmdResult(exitcode, stdout, stderr, cmd, input)
    return CmdResult(exitcode, stdout, stderr, cmd, input)
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
1005493
def run(command, cwd=None, shell=False, raiseOnError=False):
		
		returncode = subprocess.call(command, cwd=cwd, shell=shell)
		if raiseOnError == True and returncode != 0:
			raise Exception('child process ' + str(command) + ' failed with exit code ' + str(returncode))
		return returncode
1155226
def runcmd(command, command_input=None, cwd=None):
    """"""
    proc = subprocess.Popen(command, stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            cwd=cwd)
    (stdout, stderr) = proc.communicate(command_input)
    if proc.returncode != 0:
        sys.stderr.write('ABORTING: command "%s" failed w/ code %s:\n'
                         '%s\n%s' % (command, proc.returncode,
                                     stdout, stderr))
        sys.exit(proc.returncode)
    return proc.returncode, stdout, stderr