如何在 Laravel 中运行 Python 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38724318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:14:36  来源:igfitidea点击:

How to run Python Script in Laravel?

phppythonlaravel

提问by rahul16590

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

我想知道如何使用 php 代码运行 python 脚本。我尝试过不同的选择,比如

 $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?

但是无法运行python脚本。我的应用程序在 Laravel 中。是否可以使用 Laravel 调度程序作业(例如使用工匠命令)运行 python 脚本?

回答by Mihir Bhende

Some things to mention about your question :

关于您的问题要提及的一些事情:

  • I will highly recommend use symfony/processinstead 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-dataand your python script is lets say ubuntu.nbodyfor example, it will then check what permissions the python script has. Are users other than ubuntuin 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.
  • 我强烈建议symfony/process直接使用而不是 shell_exec。它已经在 Laravel 中可用。您可以轻松检查您的命令是否成功并以字符串格式等获取标准输出
  • 当您从 Web 应用程序运行 shell 脚本时,用户权限很重要。例如,laravel 网络用户是www-data,你的 python 脚本是ubuntu.nbody,例如,它会检查 python 脚本具有哪些权限。是否ubuntu允许本示例以外的用户运行它。
  • 那么如果你认为给 python 脚本 777 权限会解决权限问题,那么这也是一个风险。
  • 最后但并非最不重要的是,创建一个 Laravel 控制台命令,添加将从symfony/process. 然后运行它并调试错误。一旦它工作,那么你可以在laravel的cron jon中添加它。

See thisto know mo about scheduling artisan commands.

请参阅此内容以了解有关调度 artisan 命令的信息。

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

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