所以我想知道,我在网上找到了一个脚本,该脚本每2秒输出一次覆盆子pi的温度:
import os
import time
def measure_temp():
temp = os.popen("vcgencmd measure_temp").readline()
return (temp.replace("temp=",""))
while True:
print(measure_temp())
time.sleep(1)
我还使用标准的apache方法创建了服务器和站点。在/ var / www / html中,我有一个名为“ phptest.php”的文件将对该站点进行补充,而我有一个名为“ monitor-temp.py”的python文件,其中包含上述用于输出温度的代码。
我的问题是,如何将python代码成功添加到php文件中,从而在站点上显示温度?
我可以直接使用nano phptest.php在php文件中输入python代码吗?还是我以某种方式访问python文件的php文件。
我看到很多指南都说将其添加到php文件中以执行python代码:
<?php
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>
但这对我没有任何帮助。预先谢谢你!
答案 0 :(得分:0)
您提供的Python脚本正在使用vcgencmd
CLI实用程序,仅此而已。您可以直接从PHP运行它(无需Python):
<?php
// escape shell metacharacters
$command = \escapeshellcmd('vcgencmd measure_temp');
// execute vcgencmd CLI utility directly; write it's output to a variable
$output = \shell_exec($command);
// remove redundant prefix 'temp='
$output = \str_replace('temp=', '', $output);
echo $output;
如果您仍然想通过Python脚本执行此操作,则需要指定Python解释器:
<?php
$command = \escapeshellcmd('python3 /path/to/script.py');
$output = \shell_exec($command);
echo $output;
答案 1 :(得分:0)
如果您只是入门,并且正在寻求简单性并且可以正常工作,那么您可能不知道PHP包含simple web server,您可以运行它而无需完全设置和配置Apache。< / p>
此脚本将获取Raspberry Pi温度并显示它。将其另存为server.php
:
<?php
echo '<pre>';
$output = system("/usr/bin/vcgencmd measure_temp");
echo '</pre>';
?>
您可以在没有Apache或其他类似工具的情况下从终端将其作为Web服务器运行:
php -S 0.0.0.0:8000 server.php
在您的网络浏览器中找到它:
http://RASPI_IP_ADDRESS:8000