Given a process ID for a running command and a pair of stdout/stdin
 streams, records the results of the command and returns them in a
 CommandRunResult instance.
558294
def collect_result(command, pid, host_stdout, host_stderr)
      result = CommandRunResult.new(pid, command, self)
      result.streams = {1 => host_stdout, 2 => host_stderr}
      return result
    end
128087
def output_for(cmd, options = {})
      output = StringIO.new
      execute(cmd, options.merge(:outstream => output))
      output.string
    end
788225
def run_cmd(cmd, out=os.path.devnull, err=os.path.devnull):
    

    logger.debug(' '.join(cmd))
    with open(out, 'w') as hout:
        proc = subprocess.Popen(cmd, stdout=hout, stderr=subprocess.PIPE)
        err_msg = proc.communicate()[1].decode()
    with open(err, 'w') as herr:
        herr.write(str(err_msg))
    msg = '({}) {}'.format(' '.join(cmd), err_msg)
    if proc.returncode != 0:
        logger.error(msg)
        raise RuntimeError(msg)
1247768
def run_command(cmd, redirect_output=True, check_exit_code=True):
    
    if redirect_output:
        stdout = subprocess.PIPE
    else:
        stdout = None
    proc = subprocess.Popen(cmd, cwd=ROOT, stdout=stdout)
    output = proc.communicate()[0]
    if check_exit_code and proc.returncode != 0:
        raise Exception('Command "%s" failed.\n%s' % (' '.join(cmd), output))
    return output
1274745
def get_pipe_series_output(commands: Sequence[str],
                           stdinput: BinaryIO = None) -> bytes:
    
    # Python arrays indexes are zero-based, i.e. an array is indexed from
    # 0 to len(array)-1.
    # The range/xrange commands, by default, start at 0 and go to one less
    # than the maximum specified.

    # print commands
    processes = []  # type: List[subprocess.Popen]
    for i in range(len(commands)):
        if i == 0:  # first processes
            processes.append(
                subprocess.Popen(
                    shlex.split(commands[i]),
                    stdin=subprocess.PIPE,
                    stdout=subprocess.PIPE
                )
            )
        else:  # subsequent ones
            processes.append(
                subprocess.Popen(
                    shlex.split(commands[i]),
                    stdin=processes[i - 1].stdout,
                    stdout=subprocess.PIPE
                )
            )
    return processes[len(processes) - 1].communicate(stdinput)[0]
520262
def run(pipeline_id, verbose, use_cache, dirty, force, concurrency, slave):
    """"""
    exitcode = 0

    running = []
    progress = {}

    def progress_cb(report):
        pid, count, success, *_, stats = report

        print('\x1b[%sA' % (1+len(running)))
        if pid not in progress:
            running.append(pid)
        progress[pid] = count, success

        for pid in running:
            count, success = progress[pid]
            if success is None:
                if count == 0:
                    print('\x1b[2K%s: \x1b[31m%s\x1b[0m' % (pid, 'WAITING FOR OUTPUT'))
                else:
                    print('\x1b[2K%s: \x1b[33mRUNNING, processed %s rows\x1b[0m' % (pid, count))
            else:
                if success:
                    print('\x1b[2K%s: \x1b[32mSUCCESS, processed %s rows\x1b[0m' % (pid, count))
                else:
                    print('\x1b[2K%s: \x1b[31mFAILURE, processed %s rows\x1b[0m' % (pid, count))

    results = run_pipelines(pipeline_id, '.', use_cache,
                            dirty, force, concurrency,
                            verbose, progress_cb if not verbose else None,
                            slave)
    if not slave:
        logging.info('RESULTS:')
        errd = False
        for result in results:
            stats = user_facing_stats(result.stats)
            errd = errd or result.errors or not result.success
            logging.info('%s: %s %s%s',
                         'SUCCESS' if result.success else 'FAILURE',
                         result.pipeline_id,
                         repr(stats) if stats is not None else '',
                         (
                            '\nERROR log from processor %s:\n+--------\n| ' % result.errors[0] +
                            '\n| '.join(result.errors[1:]) +
                            '\n+--------'
                         ) if result.errors else '')
    else:
        result_obj = []
        errd = False
        for result in results:
            errd = errd or result.errors or not result.success
            stats = user_facing_stats(result.stats)
            result_obj.append(dict(
                success=result.success,
                pipeline_id=result.pipeline_id,
                stats=result.stats,
                errors=result.errors
            ))
            json.dump(result_obj, sys.stderr)

    if errd:
        exitcode = 1

    exit(exitcode)
782074
def run_command_for_code(command):
    
    process = subprocess.Popen(
        command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    process.communicate()
    exit_code = process.returncode
    return exit_code
48330
def get_command_from_result(script, result, debug=False):
    
    if not debug:
        command = "python waf --run \"" + script + " " + " ".join(
            ['--%s=%s' % (param, value) for param, value in
             result['params'].items()]) + "\""
    else:
        command = "python waf --run " + script + " --command-template=\"" +\
            "gdb --args %s " + " ".join(['--%s=%s' % (param, value) for
                                         param, value in
                                         result['params'].items()]) + "\""
    return command
1046251
def _capture_stdout(callable: Callable[..., CaptureResult], *args, **kwargs) -> CaptureResult:
        
        stream = StringIO()
        with redirect_stdout(stream):
            return_value = callable(*args, **kwargs)
        assert return_value.stdout is None, "stdout appears to have already been captured"
        return CaptureResult(return_value=return_value.return_value, stdout=stream.getvalue(),
                             stderr=return_value.stderr, exception=return_value.exception)
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
62935
def show_run(command_history_id):
    
    from pprint import pprint
    from .config import ConfigStore
    from .database import DataBase
    db = DataBase(ConfigStore().db_path)
    with db.connection():
        for ch_id in command_history_id:
            crec = db.get_full_command_record(ch_id)
            pprint(crec.__dict__)
            print("")
559032
async def checked_run(*cmd):
  

  # Start the subprocess.
  logging.info('Running: %s', expand_cmd_str(cmd))
  with logged_timer('{} finished'.format(get_cmd_name(cmd))):
    p = await asyncio.create_subprocess_exec(
        *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)

    # Stream output from the process stdout.
    chunks = []
    while True:
      chunk = await p.stdout.read(16 * 1024)
      if not chunk:
        break
      chunks.append(chunk)

    # Wait for the process to finish, check it was successful & build stdout.
    await p.wait()
    stdout = b''.join(chunks).decode()[:-1]
    if p.returncode:
      raise RuntimeError('Return code {} from process: {}\n{}'.format(
          p.returncode, expand_cmd_str(cmd), stdout))

    return stdout
376057
static function execSystemCommand($cmd, &$return_code) {
	
		if (!function_exists('proc_open') || !function_exists('proc_close')) {
			throw new RuntimeException("Process execution functions are missing!");
		}
		
		$proc = proc_open($cmd, array(
			0 => array('pipe', 'r'),// stdin
			1 => array('pipe', 'w'),// stdout
			2 => array('pipe', 'w'),// stderr
		), $pipes);
	
		if ($proc===false) {
			throw new IOException("Error while calling proc_open");
		}
	
		$output = stream_get_contents($pipes[1]).' '.stream_get_contents($pipes[2]);
	
		$return_code = proc_close($proc);
	
		return $output;
	}
394115
def execute(self, command):
        

        logger.info("running command %s", command)
        cmd = ["podman", "exec", self.get_id()] + command
        output = run_cmd(cmd, return_output=True)

        return output
782424
def subprocess_output(command, raise_on_empty_output):
    

    # Use tempfile, allowing a larger amount of memory. The subprocess.Popen
    # docs warn that the data read is buffered in memory. They suggest not to
    # use subprocess.PIPE if the data size is large or unlimited.
    with tempfile.TemporaryFile() as stdout_f, tempfile.TemporaryFile() as stderr_f:
        proc = subprocess.Popen(command, stdout=stdout_f, stderr=stderr_f)
        proc.wait()
        stderr_f.seek(0)
        err = stderr_f.read()
        stdout_f.seek(0)
        output = stdout_f.read()

    if not output and raise_on_empty_output:
        raise SubprocessOutputEmptyError("get_subprocess_output expected output but had none.")

    return output, err, proc.returncode
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
444896
def command(results_dir, result_id):
    
    campaign = sem.CampaignManager.load(results_dir)

    result = campaign.db.get_results(result_id=result_id)[0]

    click.echo("Simulation command:")
    click.echo(sem.utils.get_command_from_result(campaign.db.get_script(),
                                                 result))
    click.echo("Debug command:")
    click.echo(sem.utils.get_command_from_result(campaign.db.get_script(),
                                                 result,
                                                 debug=True))