简体   繁体   English

无法从PHP运行Python脚本并将打印输出到浏览器

[英]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: 所以这是如何复制我的问题:

  1. Boot up a t2.micro EC2 server on Amazon AWS 在Amazon AWS上启动t2.micro EC2服务器
  2. Configure it as a web server ( instructions here ) 将其配置为Web服务器( 此处说明
  3. Upload an index.php file to /var/www/html with the following code: 使用以下代码将index.php文件上传到/ var / www / html:

<?php 
$command = escapeshellcmd('sudo /usr/bin/python '.__DIR__.'/script.py');
$output = shell_exec($command);
exit(var_dump($output));
  1. Upload a script.py file to the same directory with the following code: 使用以下代码将script.py文件上传到同一目录:

#!/usr/bin/python

print('Hello!')
  1. Go to the AWS public URL. 转到AWS公共URL。 The response you will get is "NULL" 您将获得的响应为“ NULL”

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM