Execute a command locally

@param string $cmd Command to execute
@param int $timeout Seconds to wait
@return Process
512078
public function runLocalCommand($cmd, $timeout = 120)
    {
        $this->log($cmd, LogLevel::INFO);

        $process = new Process($cmd);
        $process->setTimeout($timeout);
        $process->run();

        $this->log($process->getOutput(), LogLevel::DEBUG);
        if (!$process->isSuccessful()) {
            $this->log($process->getErrorOutput(), LogLevel::ERROR);
        }

        return $process;
    }
83856
protected static function exec($cmd, $args)
    {
        $command = self::which($cmd) . ' ' . join(' ', array_map('escapeshellarg', $args));
        
        $descriptorspec = array(
           1 => array("pipe", "w"),  // stdout
           2 => array("pipe", "w")   // stderr
        );

        $handle = proc_open($command, $descriptorspec, $pipes);
        if (!$handle) throw new \Exception("Failed to run sox command");
        
        $out = stream_get_contents($pipes[1]);
        $err = stream_get_contents($pipes[2]);
        
        $ret = proc_close($handle);
        if ($ret != 0) throw new \Exception("$cmd command failed. " . trim($err));

        return $out ?: $err;
    }
294467
public function setTimeout($timeout = 60)
    {
        $this->timeout = $timeout;
        $this->debug->info(__FUNCTION__, 'setTimeout: ', $this->timeout);

        return $this;
    }
815618
public function run($hostname, string $command, array $config = [])
    {
        $defaults = [
            'timeout' => Deployer::getDefault('default_timeout', 300),
            'tty' => false,
        ];
        $config = array_merge($defaults, $config);

        $this->pop->command($hostname, $command);

        $process = new Process($command);
        $process
            ->setTimeout($config['timeout'])
            ->setTty($config['tty'])
            ->mustRun($this->pop->callback($hostname));

        return $process->getOutput();
    }
992384
def wait(self, timeout=None):
        
        timeout = ["--interval=%s" % timeout] if timeout else []
        cmdline = ["podman", "wait"] + timeout + [self._id or self.get_id()]
        return run_cmd(cmdline, return_output=True)
843668
public function timeout($timeout = null)
    {
        $this->timeout = (null === $timeout) ? $this->defaultTimeout : $timeout;
        return $this;
    }
432791
private function doRequest($cmd, $args = array())
    {
        clearstatcache();
        $args['domain'] = $this->domain;
        $params = http_build_query($args);

        $this->connect();

        fwrite($this->socket, "{$cmd} {$params}\n");
        $line = fgets($this->socket);

        $words = explode(' ', $line);

        if ($words[0] == 'OK') {
            parse_str(trim($words[1]), $result);
        } else {
            $errorName = empty($words[1]) ? null : $words[1];

            switch ($errorName) {
                case 'unknown_key':
                    $errorCode = static::ERR_UNKNOWN_KEY;
                    break;
                case 'empty_file':
                    $errorCode = static::ERR_EMPTY_FILE;
                    break;
                case 'none_match':
                    $errorCode = static::ERR_NONE_MATCH;
                    break;
                case 'key_exists':
                    $errorCode = static::ERR_KEY_EXISTS;
                    break;
                default:
                    $errorCode = static::ERR_OTHER;
            }

            throw new \RuntimeException(
                sprintf('Error response: %s', $line),
                $errorCode
            );
        }

        return $result;
    }
1343464
public function execute($cmd, $data)
    {
        // Use pipes for STDIN, STDOUT, and STDERR
        $descr = array(
          0 => array(
            'pipe',
            'r'
          ) ,
          1 => array(
            'pipe',
            'w'
          ) ,
          2 => array(
            'pipe',
            'w'
          )
        );
        $pipes = [];

        // Start process, telling it to use STDIN for input and STDOUT for output.
        $cmd = escapeshellcmd($cmd);
        $process = proc_open($cmd, $descr, $pipes);

        // Get the data into pipe only if data is resource
        if (gettype($data) == "resource") {
            // Stream input to STDIN
            while (!feof($data)) {
                fwrite($pipes[0], fread($data, 1024));
            }

            // Close STDIN and the source data.
            fclose($pipes[0]);
            fclose($data);
        }

        // Wait for process to finish while reading STDOUT to a temp stream.
        // Otherwise the process can block indefinitely if STODUT gets bigger
        // than 4kb.
        $this->output = fopen("php://temp", 'w+');
        $exit_code = null;
        while ($exit_code === null) {
            $status = proc_get_status($process);
            if ($status['running'] === false) {
                $exit_code = $status['exitcode'];
            }

            $chunk = stream_get_contents($pipes[1]);
            if ($chunk !== false) {
                fwrite($this->output, $chunk);
            }
        }

        // Close STDOUT
        fclose($pipes[1]);

        // On error, extract message from STDERR and throw an exception.
        if ($exit_code != 0) {
            $msg = stream_get_contents($pipes[2]);
            $this->cleanup($pipes, $this->output, $process);
            if ($this->log) {
                $this->log->error('Process exited with non-zero code.', [
                  'exit_code' => $exit_code,
                  'stderr' => $msg,
                ]);
            }
            throw new \RuntimeException($msg, 500);
        }

        // Return a function that streams the output.
        return function () use ($pipes, $process) {
            rewind($this->output);
            while (!feof($this->output)) {
                echo fread($this->output, 1024);
                ob_flush();
                flush();
            }
            $this->cleanup($pipes, $this->output, $process);
        };
    }
258226
protected function executeCmd($command)
    {
        $process = new $this->processClass($command);
        $process->run();

        if (false === $process->isSuccessful() && strlen($process->getErrorOutput()) > 0) {
            throw new \RuntimeException($process->getErrorOutput());
        }

        return $process->getOutput();
    }
1159007
public function execute($cmd, $failOnError = true)
    {
        $command = $this->createSupervisorControlCommand($cmd);
        $this->logger->debug('Executing: ' . $command);
        $p = new Process($command);
        $p->setWorkingDirectory($this->applicationDirectory);
        $p->run();
        if ($failOnError) {
            if ($p->getExitCode() !== 0) {
                $this->logger->critical(sprintf('supervisorctl returns code: %s', $p->getExitCodeText()));
            }
            $this->logger->debug('supervisorctl output: '. $p->getOutput());

            if ($p->getExitCode() !== 0) {
                throw new ProcessException($p);
            }
        }

        return $p;
    }
935129
function exec (cmd) {
  debug('executing cmd', cmd)
  child_process.exec(cmd, function (err, stdout, stderr) {
    debug('command completed')
  })
}
629802
public function execute($cmd, &$captureOutput = null)
    {
        $isInteractive = $this->container->get('INTERACTIVE');
        $process = $this->createProcess($isInteractive);

        if ($isInteractive) {
            $process->setCommandLine(sprintf('/bin/bash -c \'%s\'', $cmd));
        } else {
            $process->setInput($cmd);
        }

        if (null !== $captureOutput && false === $isInteractive) {
            $process->run(function ($type, $data) use(&$captureOutput) {
                $captureOutput .= $data;
            });
        } else {
            $process->run(array($this, 'processCallback'));
        }

        $ret = $process->getExitCode();

        if ($ret != 0) {
            if ((int)$ret == Container::ABORT_EXIT_CODE) {
                throw new ExecutionAbortedException("Command '$cmd' was aborted");
            } else {
                throw new \UnexpectedValueException("Command '$cmd' failed with exit code {$ret}");
            }
        }
        return $ret;
    }
862089
async def _wait_for_cmd(self, cmd, value, timeout=OTGW_DEFAULT_TIMEOUT):
        
        if not self._connected:
            return
        try:
            return await asyncio.wait_for(self._protocol.issue_cmd(cmd, value),
                                          timeout,
                                          loop=self.loop)
        except TimeoutError:
            _LOGGER.error("Timed out waiting for command: %s, value: %s.", cmd,
                          value)
            return
        except (RuntimeError, SyntaxError, ValueError) as exc:
            _LOGGER.error("Command %s with value %s raised exception: %s", cmd,
                          value, exc)
588484
public function setAll($timeout)
    {
        $command = $this->driver->factoryCommand('timeouts', WebDriver_Command::METHOD_POST, $timeout);
        foreach ($this->cache as &$value) {
            $value = $timeout;
        }
        return $this->driver->curl($command)['value'];
    }
813513
protected function _exec($cmd, $input)
    {
        $result = ['stdout' => '', 'stderr' => '', 'return' => ''];

        $cwd = $this->getConfig('cwd');

        $proc = proc_open($cmd, [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, $cwd);
        fwrite($pipes[0], $input);
        fclose($pipes[0]);

        $result['stdout'] = stream_get_contents($pipes[1]);
        fclose($pipes[1]);

        $result['stderr'] = stream_get_contents($pipes[2]);
        fclose($pipes[2]);

        $result['return'] = proc_close($proc);

        return $result;
    }
1325773
public static function shell($sh, $cwd = null, int $timeout = 60, bool $async = false)
    {
        $process = new Process($sh, $cwd, null, null, $timeout);

        if ($async) {
            $process->start();
            $process->wait(function ($type, $buffer) {
                if (Process::ERR === $type) {
                    static::log('error', $buffer);
                }
            });
        } else {
            $process->run();

            if (! $process->isSuccessful()) {
                static::log('error', $process->getErrorOutput());
                throw new ProcessFailedException($process);
            }

            return $process->getOutput();
        }

        unset($process);
    }
606944
public static function execute( $command, $directory = null, $timeout = 120 ) {
		$directory = $directory !== null ? $directory : getcwd();

		$process = new Process( $command, null, null, null, $timeout );
		$process->setWorkingDirectory( $directory );
		$process->mustRun();

		return $process->getOutput();
	}