首页 > 解决方案 > 从 Laravel 运行 Python 脚本

问题描述

我正在尝试在 Laravel 中构建一个系统,我可以从中调用一些 python 脚本。从https://github.com/maurosoria/dirsearch开始,我将 python 脚本放置在同一台机器上并尝试在 api 调用上运行。

如果我运行shall_exec('ls -la');它会完美运行并返回结果。但是当我运行以下命令时,执行结束并且没有输出。

shall_exec("python3 dirsearch-master/dirsearch.py -u https://www.yahoo.com/ -e *");

然后我使用 https://symfony.com/doc/current/components/process.html并尝试相同的步骤

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

$process = new Process("python3 dirsearch-master/dirsearch.py -u https://www.yahoo.com/ -e *");
$process->run();

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

echo $process->getOutput();

在这种情况下,$process->run();我也没有返回任何结果。

标签: phppythonlinuxlaravelprocess

解决方案


如果需要,您可以使用自定义Artisan命令。通过运行创建一个新的 Artisan 命令php artisan make:command COMMAND_NAME。它将在app\Console\Commands您的项目目录中创建一个新的 Artisan 命令。

class Analytics extends Command{

    protected $signature = 'Run:Shell {path} {u} {e}';

    protected $description = 'Run Python Via Server Shell';

    public function __construct(){
        parent::__construct();
    }

    public function handle(){
        $output = shall_exec("python3 ".$this->argument('path')." -u ".$this->argument('u')." -e ".$this->argument('e'));
        $this->info($output);
    }
}

现在,您可以运行 artisan 命令,php artisan Run:Shell path='dirsearch-master/dirsearch.py' u='https://www.yahoo.com/' e='*'输出将打印到 CMD。你也可以从任何你想要的控制器运行这个 Artisan 命令,

// Taking Inputs from Request in Controller
Artisan::call("Run:Shell", ['path' => $request->input('path'), 'u' => $request->input('u') , 'e' => $request->input('e')]); 

事实上,你可以使用 Laravel 让整个包装器在你的服务器端运行 python。但是你应该python3在运行它之前在你的服务器上安装和配置它。


推荐阅读