[英]Run Python script from Laravel
I am trying to build a system in Laravel from which I am able to call some python scripts. 我试图在Laravel中建立一个系统,从中我可以调用一些python脚本。 Starting with https://github.com/maurosoria/dirsearch , I have placed the python script with the same machine and tried to run on api call. 从https://github.com/maurosoria/dirsearch开始,我将python脚本放置在同一台机器上,并尝试在api调用上运行。
If I run shall_exec('ls -la');
如果我运行shall_exec('ls -la');
it runs perfectly and returns me result. 它运行完美,并向我返回结果。 But when I run the following command, the execution ends and no output. 但是,当我运行以下命令时,执行结束并且没有输出。
shall_exec("python3 dirsearch-master/dirsearch.py -u https://www.yahoo.com/ -e *");
Then I used https://symfony.com/doc/current/components/process.html and try the same steps 然后我使用了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();
In this case also the $process->run();
在这种情况下, $process->run();
也是如此$process->run();
returns me no result. 没有结果。
You can use the Custom Artisan
command if you want. 您可以根据需要使用Custom Artisan
命令。 Create a new Artisan Command by running php artisan make:command COMMAND_NAME
. 通过运行php artisan make:command COMMAND_NAME
创建一个新的Artisan Command。 it will create a new Artisan command in app\\Console\\Commands
directory of your project. 它将在项目的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);
}
}
Now, you can run the artisan command as php artisan Run:Shell path='dirsearch-master/dirsearch.py' u='https://www.yahoo.com/' e='*'
and the output will be printed to CMD. 现在,您可以将artisan命令作为php artisan Run:Shell path='dirsearch-master/dirsearch.py' u='https://www.yahoo.com/' e='*'
,输出将被打印到CMD。 You can also run this Artisan command from any controller you want as, 您也可以从任何需要的控制器运行Artisan命令,
// Taking Inputs from Request in Controller
Artisan::call("Run:Shell", ['path' => $request->input('path'), 'u' => $request->input('u') , 'e' => $request->input('e')]);
In fact, you can make the entire wrapper to run the python on your server-side using Laravel. 实际上,您可以使整个包装器使用Laravel在服务器端运行python。 But you should have the python3
installed and configured on your server before running it. 但是在运行它之前,应该在服务器上安装并配置了python3
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.