解决php在树莓派中无法调用python脚本的问题

解决php在树莓派中无法调用python脚本的问题,第1张

项目场景:

以树莓派为核心的一个可以通过访问公网域名查看实时监测数据的测温仪。
通过nginx将编辑好作为在线仪表盘的php网页发送至localhost:80端口,同时使用内网穿透与域名映射将端口转发至公网。
项目的重点是在php中实现对树莓派的命令 *** 作,也就是通过php *** 作树莓派gpio,通过php运行python程序等。


问题描述

使用shell_exec()函数,命令树莓派执行python程序,获取其字符串类型的返回值,并赋值给将要在网页上显示的变量:

 $D['temp1'] = shell_exec("python dataread1.py"); ?>
<?php $D['temp2'] = shell_exec("python dataread2.py"); ?>

<div class="text-center" style="margin:20px; padding: 10px 0 10px 0; background-color:#FAFAFA; border-radius: 3px;">
<div class="label">环境温度</div></div>
<div id="temp1" style="font-size: 150%; font-weight: bolder;">
<?php echo($D['temp1']); ?></div></div>
<div class="text-center" style="margin:20px; padding: 10px 0 10px 0; background-color:#FAFAFA; border-radius: 3px;">
<div class="label">测量温度</div></div>
<div id="temp2" style="font-size: 150%; font-weight: bolder;">
<?php echo($D['temp2']); ?></div></div>

但测试发现,网页没有按照预期一般地显示数据。显然,shell_exce()并未起到作用。


原因分析:

shell_exce()函数更换为system()函数、exce()函数,均为无显示。
初步推测是nginx权限不够,无法在php中调用涉及gpio *** 作的python脚本。
使用网传较广的两个方法给nginx加权限:
1、添加www-data用户的root权限:

2、将网页根目录设为777读写权限:

执行以上步骤后仍未能解决问题。


解决方案:

既然直接调用python脚本不起作用,那就隔山打牛,利用sh运行py文件。

新建sh文件,分别命名为dataread1.shdataread2.sh

sudo python dataread1.py
sudo python dataread2.py

并将php部分修改为:

 $D['temp1'] = shell_exec("sudo sh dataread1.sh"); ?>
<?php $D['temp2'] = shell_exec("sudo sh dataread2.sh"); ?>

经测试,网页可正常显示数据。

由于root权限,该方法限仅出站流量使用。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/915605.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存