這篇文章主要介紹在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's 的 Process 組件。
使用這種方法,我可以拋出一個自定義異常,記錄命令和輸出,或者是記錄到日志以尋找問題。
以上是“在Laravel中如何執行Shell命令”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。