php运行python脚本_无法从PHP文件执行Python脚本

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:

Light Controller

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");

}

?>

Light ON 

Light OFF

解决方案

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

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

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

then

change group:

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

make it executabel

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

try it

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

I hope it works ;)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值