如何在Laravel中运行Python脚本? [英] How to run Python Script in Laravel?

查看:555
本文介绍了如何在Laravel中运行Python脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用php代码运行python脚本.我尝试过其他选择,例如

 $output = exec("python  /var/GAAutomationScript.py");

 $command = escapeshellcmd('/var/GAAutomationScript.py');
 $output = shell_exec($command);

但是无法运行python脚本.我的应用程序在Laravel中.是否可以使用Laravel Scheduler作业运行python脚本,例如使用工匠命令?

解决方案

关于您的问题,有几点要提:

  • 我强烈建议使用 symfony/process 而不是直接使用shell_exec.它已经在laravel中可用.您可以轻松检查命令是否成功,并以字符串格式等获取标准输出
  • 从Web应用程序运行Shell脚本时,用户权限很重要.例如,laravel Web用户为www-data,而您的python脚本为例如ubuntu.nbody,它将检查python脚本具有哪些权限.在此示例中,是否允许除ubuntu之外的其他用户运行它.
  • 然后,如果您认为将777权限授予python脚本将摆脱权限问题,那也有风险.
  • 最后但并非最不重要的一点是,创建一个laravel控制台命令,添加将运行symfony/process中的python脚本的代码段.然后运行它并调试错误.一旦工作,您可以将其添加为laravel的cron jon中的内容.

请参阅以了解有关调度工匠命令的信息. /p>

您还可以避免创建artisan命令并直接添加shell,因为它在内部使用symfony/process. 请参阅以获取该参考

I wanted to know how to run python script using php code. I have tried different options like

 $output = exec("python  /var/GAAutomationScript.py");

 $command = escapeshellcmd('/var/GAAutomationScript.py');
 $output = shell_exec($command);

But unable to run the python script. My application is in Laravel. Is it possible to run python script using Laravel scheduler jobs e.g. using artisan commands?

解决方案

Some things to mention about your question :

  • I will highly recommend use symfony/process instead of shell_exec directly. It is already available in laravel. You can check easily if your command is successful or not and get standard output in string format etc
  • When you run a shell script from a web app, the user permissions matter. For example, the laravel web user is www-data and your python script is lets say ubuntu.nbody for example, it will then check what permissions the python script has. Are users other than ubuntu in this example are allowed to run it.
  • Then if you think giving 777 permissions to python script will get rid of the permission problem then thats a risk too.
  • Last but not the least, create a laravel console command, add the snippet which would run python script from symfony/process. Then run it and debug the errors. once it works then you can add that as in laravel's cron jon.

See this to know mo about scheduling artisan commands.

You can also avoid creating artisan command and add shell directly, as it internally uses symfony/process. See this for that reference

这篇关于如何在Laravel中运行Python脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆