Running python script in Laravel

人走茶凉 提交于 2019-11-27 20:15:56

Use Symfony Process. https://symfony.com/doc/current/components/process.html

Install:

composer require symfony/process

Code:

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process('python /path/to/your_script.py');
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();

The solution that worked for me was to add 2>&1 to the end.

shell_exec("python path/to/script.py 2>&1");

The issue I was having was no error and no response, I had the wrong path to the script but no way of knowing. 2>&1 will redirect the debug info to be the result.

In the shell, what does " 2>&1 " mean?

Would be handy to use Symfony Process. https://symfony.com/doc/current/components/process.html

Make sure symphony is available to use in your project

composer show symphony/process

If not installed do composer require symfony/process

And then do some thing like

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

//$process = new Process('python /path/to/your_script.py'); //This won't be handy when going to pass argument
$process = new Process(['python','/path/to/your_script.py',$arg(optional)]);
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!