php - 从 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();
我也没有返回任何结果。
解决方案
如果需要,您可以使用自定义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
在运行它之前在你的服务器上安装和配置它。
推荐阅读
- javascript - 如何显示来自表格条目的计算?
- python - Python:根据日期时间逐行扩展数据框
- mysql - 获取过去 12 个月内没有活动的用户
- java - 使用 Spring JPA 在表中使用双引号将字符串值持久化
- laravel - Laravel 之谜 - 两种相似的项目类型在同一用例中产生 2 个不同的查询字符串
- scala - 不推荐使用 ReactiveMongo 中的方法 find 。使用带有可选投影的“查找”
- javascript - scss中的反向查找选择器
- javascript - 嵌入数据表组件时获取函数内部的行数据
- liquibase - Liquibase 没有按依赖顺序执行更改日志文件
- excel - 在两个工作簿之间复制和粘贴动态范围