在 Laravel 中执行 Shell 命令
shell_exec()
和 exec()
都可以执行 shell 命令。
如果你的命令不知道因为什么原因而崩溃,你将不会知道其原因 —— 因为shell_exec()
和 exec()
不会抛出异常,他们只是默默地执行失败了。😱
这是我的解决方案:
use Symfony\Component\Process\Process;
class ShellCommand
{
public static function execute($cmd): string
{
$process = Process::fromShellCommandline($cmd);
$processOutput = '';
$captureOutput = function ($type, $line) use (&$processOutput) {
$processOutput .= $line;
};
$process->setTimeout(null)
->run($captureOutput);
if ($process->getExitCode()) {
$exception = new ShellCommandFailedException($cmd . " - " . $processOutput);
report($exception);
throw $exception;
}
return $processOutput;
}
}
- 它使用了 Symfony 的 Process 组件。 ✨
使用这种方法,我可以抛出一个自定义异常,记录命令和输出,或者是记录到日志以寻找问题。
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。