run shell command

	@param cmd: command to execute
	@param timeout: timeout for command execution

	@return: (return code from command, command 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)
379819
public void execute(CommandHandler handler,
            int timeout,
            TimeUnit unit) throws
            CommandLineException,
            InterruptedException, ExecutionException, TimeoutException {
        ExecutableBuilder builder = new ExecutableBuilder() {
            CommandContext c = newTimeoutCommandContext(ctx);
            @Override
            public Executable build() {
                return () -> {
                    handler.handle(c);
                };
            }

            @Override
            public CommandContext getCommandContext() {
                return c;
            }
        };
        execute(builder, timeout, unit);
    }
95428
def run(command):
    '''
    
    '''
    if isinstance(command, list):
        command = ' '.join(command)
    out = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return (out.returncode, _prepare(out.stdout), _prepare(out.stderr))
1349918
function run(cmd) {
  try {
    if (isWindows)
      cmd = 'cmd /C ' + cmd;
    var code = shell.exec(cmd);
    return code;
  } catch (err) {
    if (err) {
      console.error(err)
    }
    return 1;
  }
}
1371951
def run(command, input=None, exit=0, shell=False):
        
        if isinstance(input, str):
            input = input.encode()

        # Only pipe stdin if we have input to pipe.
        stdin = {} if input is None else {"stdin": subprocess.PIPE}
        try:
            child = subprocess.Popen(command, stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE, **stdin)
        except FileNotFoundError as e:
            # Extract name of command.
            name = command.split(' ', 1)[0] if isinstance(command, str) else command[0]
            raise DependencyError(name)

        stdout, _ = child.communicate(input=input)
        if exit is not None and child.returncode != exit:
            raise Error("failed to stylecheck code")
        return stdout.decode()
570293
def run_cmd(call, cmd, *, echo=True, **kwargs):
    """"""
    if echo:
        print('$> ' + ' '.join(map(pipes.quote, cmd)))
    return call(cmd, **kwargs)
1228251
def execute_command(self, *args, **options):
        ""
        pool = self.connection_pool
        command_name = args[0]
        connection = pool.get_connection(command_name, **options)
        try:
            connection.send_command(*args)
            return self.parse_response(connection, command_name, **options)
        except (ConnectionError, TimeoutError) as e:
            connection.disconnect()
            if not (connection.retry_on_timeout and
                    isinstance(e, TimeoutError)):
                raise
            connection.send_command(*args)
            return self.parse_response(connection, command_name, **options)
        finally:
            pool.release(connection)
858163
def _exec_cmd(command):
    """"""
    proc = sp.Popen(command,
                    stdout=sp.PIPE,
                    shell=True)
    if six.PY2:
        res = proc.communicate()[0]
    else:
        res = proc.communicate(timeout=5)[0]
    return res, proc.returncode
1140647
def _exec(cmd):
        
        process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

        # pylint: disable=unexpected-keyword-arg
        (stdout, stderr) = process.communicate(timeout=defaults.DEFAULT_VCS_TIMEOUT)

        return process.returncode, stdout.decode(), stderr.decode()
319666
def run_shell(cmd, timeout=60, verbose=False):
    """"""
    retcode = None
    try:
        p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, executable='/bin/bash')
        continue_running = True
    except Exception as e:
        yield("Failed: %s" % e)
        continue_running = False

    while continue_running:
        try:
            line = p.stdout.readline()
            if verbose and line:
                yield(line)
            elif line.strip():
                yield(line.strip())
        except Exception:
            pass

        try:
            data = irc.recv(4096)
        except Exception as e:
            data = ""
            retcode = p.poll()  # returns None while subprocess is running

        if '!cancel' in data:
            retcode = "Cancelled live output reading. You have to kill the process manually."
            yield "[X]: %s" % retcode
            break

        elif retcode is not None:
            try:
                line = p.stdout.read()
            except:
                retcode = "Too much output, read timed out. Process is still running in background."

            if verbose and line:
                yield line

            if retcode != 0:
                yield "[X]: %s" % retcode
            elif retcode == 0 and verbose:
                yield "[√]"

            break
581536
public static function exec($cmd, $timeout, &$code)
    {
        $code = -11;
        // File descriptors passed to the process.
        $descriptors = [
            0 => ['pipe', 'r'],  // stdin
            1 => ['pipe', 'w'],  // stdout
            2 => ['pipe', 'w']   // stderr
        ];
        
        // Start the process.
        $process = proc_open('exec ' . $cmd, $descriptors, $pipes);
        if (!is_resource($process)) {
            throw new \Exception('Could not execute process');
        }
        
        // Set the stdout stream to none-blocking.
        stream_set_blocking($pipes[1], 0);
        stream_set_blocking($pipes[2], 0);
        
        // Turn the timeout into microseconds.
        $timeout *= 1000000;
        
        // Output buffer.
        $buffer = '';
        
        // While we have time to wait.
        while ($timeout > 0) {
            $start = microtime(true);
            // Wait until we have output or the timer expired.
            $read  = [$pipes[1]];
            $write = $other = [];
            stream_select($read, $write, $other, 0, $timeout);
            
            // Get the status of the process.
            // Do this before we read from the stream,
            // this way we can't lose the last bit of output if the process dies between these functions.
            $status = proc_get_status($process);
            if (false === $status['running']) {
                $code = $status['exitcode'];
            }
            
            // Read the contents from the buffer.
            // This function will always return immediately as the stream is none-blocking.
            $buffer .= stream_get_contents($pipes[1]);
            
            if (!$status['running']) {
                break; // Break from this loop if the process exited before the timeout.
            }
            
            // Subtract the number of microseconds that we waited.
            $timeout -= (microtime(true) - $start) * 1000000;
        }
        // Check if there were any errors.
        $errors = stream_get_contents($pipes[2]);
        if (!empty($errors)) {
            throw new \Exception($errors);
        }
        // Kill the process in case the timeout expired and it's still running.
        // If the process already exited this won't do anything.
        proc_terminate($process, 9);
        
        // Close all streams.
        fclose($pipes[0]);
        fclose($pipes[1]);
        fclose($pipes[2]);
        
        proc_close($process);
        
        return $buffer;
    }
348087
def run(cmd, input=None, capture_output=False, check=False, quiet=False, **kwargs):
    """"""
    if input is not None:
        kwargs['stdin'] = subprocess.PIPE
    if capture_output:
        kwargs['stdout'] = kwargs['stderr'] = subprocess.PIPE

    try:
        proc = subprocess.Popen(cmd, startupinfo=get_startupinfo(), **kwargs)
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise ExecutableNotFound(cmd)
        else:
            raise

    out, err = proc.communicate(input)

    if not quiet and err:
        stderr_write_bytes(err, flush=True)
    if check and proc.returncode:
        raise CalledProcessError(proc.returncode, cmd, output=out, stderr=err)

    return out, err
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
755481
protected function executeCommand($command, $timeout = 300, $callback = null)
    {
        $process = new Process($this->prepare($command), $this->cwd, null, null, $timeout);
        $process->run($callback);
        if (!$process->isSuccessful()) {
            throw new \RuntimeException(sprintf('An error occurred when executing the "%s" command.', $command));
        }
    }
431533
def execute(self, command, timeout=1):
        
        self.send(command)
        return self.read_untill(timeout)
339293
def run_command(
        cls,
        cmd,  # type: List[str]
        show_stdout=True,  # type: bool
        cwd=None,  # type: Optional[str]
        on_returncode='raise',  # type: str
        extra_ok_returncodes=None,  # type: Optional[Iterable[int]]
        command_desc=None,  # type: Optional[str]
        extra_environ=None,  # type: Optional[Mapping[str, Any]]
        spinner=None  # type: Optional[SpinnerInterface]
    ):
        # type: (...) -> Optional[Text]
        
        cmd = [cls.name] + cmd
        try:
            return call_subprocess(cmd, show_stdout, cwd,
                                   on_returncode=on_returncode,
                                   extra_ok_returncodes=extra_ok_returncodes,
                                   command_desc=command_desc,
                                   extra_environ=extra_environ,
                                   unset_environ=cls.unset_environ,
                                   spinner=spinner)
        except OSError as e:
            # errno.ENOENT = no such file or directory
            # In other words, the VCS executable isn't available
            if e.errno == errno.ENOENT:
                raise BadCommand(
                    'Cannot find command %r - do you have '
                    '%r installed and in your '
                    'PATH?' % (cls.name, cls.name))
            else:
                raise
347498
public function execute($command, $timeout = 300, $callback = null)
    {
        if ($timeout > 0 || is_callable($callback)) {
            $this->executeCommand($command, $timeout, $callback);
        } else {
            $this->executeCommandInBackground($command);
        }
    }