无法从 PHP 文档执行 Python 脚本 [英] Can't execute Python script from PHP document

查看:33
本文介绍了无法从 PHP 文档执行 Python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Raspberry Pi 上的 Apache 服务器上运行一个 PHP 文档,我希望它在单击按钮时运行一个文件.我在命令下放置了一些回显命令以使文件运行并打印出来但文件没有运行.index.php 文件和lightson.py 和lightsoff.py 文件都在同一个目录(/var/www) 中,我添加了#!/usr/bin/env python 到两个文件的顶部,并使用 chmod +x lightson.py 使它们可执行.如果我从 shell 运行命令,它会工作并打开灯,就像我想要的一样,使用与文件中完全相同的命令,但它不会通过命令运行.代码:

I am running a PHP document on an Apache server on my Raspberry Pi and I want it to run a file when a button is clicked. I put some echo commands under the command to make the file run and it prints out but the file doesn't run. The index.php file and lightson.py and lightsoff.py files are all in the same directory (/var/www) and I have added #!/usr/bin/env python to the top of both files and made them executable by using chmod +x lightson.py. If I run the command from the shell it works and turns on the light just like I want with the exact same command as in the file but yet it wont run through the command. The code:

<html>
<head>
<title>Light Controller</title>
</head>


<?php
if (isset($_POST['LightON']))
{
shell_exec("sudo python /var/www/lightson.py");
echo("on");
}
if (isset($_POST['LightOFF']))
{
shell_exec("sudo python /var/www/lightsoff.py");
echo("Off");
}
?>

<form method="post">
<button name="LightON">Light ON</button>&nbsp;
<button name="LightOFF">Light OFF</button><br><br>
</form> 


</html>

推荐答案

正如你所说,你运行它就像 apache->php->shell_exec(SUDO..)

as you said you are running it like apache->php->shell_exec(SUDO..)

所以 apache 用户必须在 sudoers 文件中,最好不要给 apache sudo 而是给 apache (www-data) 用户运行你的 python 程序的权限

So the apache user has to be in sudoers file, better you don't give sudo to apache instead give apache (www-data) user right to run your python program

把第一行放在你的python脚本中:#!/usr/bin/env python 这样脚本就知道用哪个程序打开它..

put first line in your python script: #!/usr/bin/env python so the script knows which program to open it with..

然后

更改组:

chgrp www-data /path/to/python-script.py

使其可执行

chmod +x /path/to/python-script.py

试试

shell_exec("/path/to/python-script.py");

我希望它有效;)

提示:Apache 和 PHP 用于提供文档和字符串,如果您想要某种控制和 API,请从 nodejs 和 https://www.npmjs.com/package/rpi-gpio 包.这样,您的可靠自动化环境就有了一个位置

TIPP: Apache and PHP are for delivering Documents and Strings, if you want some kind of control and an API start with nodejs and https://www.npmjs.com/package/rpi-gpio package. This way you will have one place for your solid automation environment

这篇关于无法从 PHP 文档执行 Python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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