说说在Laravel中怎么执行Shell命令 ?

 3841

下面带大家介绍关于怎么在 Laravel 中执行 Shell 命令,希望对大家有所帮助!


说说在Laravel中怎么执行Shell命令 ?


shell_exec() 和 exec() 都可以执行 shell 命令。

如果你的命令不知道因为什么原因而崩溃,你将不会知道其原因 —— 因为shell_exec() 和 exec() 不会抛出异常,他们只是默默地执行失败了。

这是我的解决方案:

  1. use Symfony\Component\Process\Process;
  2.  
  3. class ShellCommand
  4. {
  5.     public static function execute($cmd): string
  6.     {
  7.         $process = Process::fromShellCommandline($cmd);
  8.  
  9.         $processOutput = '';
  10.  
  11.         $captureOutput = function ($type, $line) use (&$processOutput) {
  12.             $processOutput .= $line;
  13.         };
  14.  
  15.         $process->setTimeout(null)
  16.             ->run($captureOutput);
  17.  
  18.         if ($process->getExitCode()) {
  19.             $exception = new ShellCommandFailedException($cmd . " - " . $processOutput);
  20.             report($exception);
  21.  
  22.             throw $exception;
  23.         }
  24.  
  25.         return $processOutput;
  26.     }
  27. }

它使用了 Symfony's 的 Process 组件。 

使用这种方法,我可以抛出一个自定义异常,记录命令和输出,或者是记录到日志以寻找问题。

原文地址:https://dev.to/kodeas/executing-shell-commands-in-laravel-1098

译文地址:https://learnku.com/laravel/t/63048


TAG标签:
本文网址:https://www.zztuku.com/index.php/detail-10217.html
站长图库 - 说说在Laravel中怎么执行Shell命令 ?
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐