[英]Unable to run Python Script from PHP and print output to browser
I've seen a lot of other people running into a similar problem where they can't run Python scripts from PHP. 我见过很多其他人遇到类似的问题,他们无法从PHP运行Python脚本。 I'm having the same situation, but I have tried all of the solutions that people recommended, but still no luck.
我遇到的情况也一样,但是我尝试了人们推荐的所有解决方案,但还是没有运气。 I also have a fresh system install and have made my scripts as simple as possible.
我也有全新的系统安装,并且使脚本尽可能简单。 Regardless of what I do, shell_exec() returns NULL.
无论我做什么,shell_exec()都会返回NULL。
So here is how to replicate my issue: 所以这是如何复制我的问题:
<?php
$command = escapeshellcmd('sudo /usr/bin/python '.__DIR__.'/script.py');
$output = shell_exec($command);
exit(var_dump($output));
#!/usr/bin/python
print('Hello!')
So to try to solve this issue, I also changed the user group of the .py file to "apache" and I ran chmod +x on the .py file. 因此,为尝试解决此问题,我还将.py文件的用户组更改为“ apache”,并在.py文件上运行了chmod + x。 I confirmed that ec2-user AND apache are in the sudo group.
我确认ec2-user和apache在sudo组中。 Still no luck!
还是没有运气! So what haven't I tried?
所以我没有尝试过什么? What am I missing or where can I go looking for error logs?
我缺少什么,或者在哪里可以找到错误日志?
Using the file constant __FILE__
to determine the path to your pyhton script only works, if you apply the dirname
function to it - otherwhise you would get something like /var/www/html/script.php/script.py
, but you actually want only /var/www/html/script.py
. 使用文件常量
__FILE__
来确定pyhton脚本的路径仅在将dirname
函数应用于该路径的情况下才有效-否则,您会得到类似/var/www/html/script.php/script.py
,但是您实际上想要仅/var/www/html/script.py
。
There are two simple solutions. 有两种简单的解决方案。 Use
dirname
or directly the __DIR__
constant. 使用
dirname
或直接使用__DIR__
常量。
$command = escapeshellcmd('sudo /usr/bin/python ' . __DIR__ . '/script.py');
or 要么
$command = escapeshellcmd('sudo /usr/bin/python ' . dirname(__FILE__) . '/script.py');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.