Skip to main content
 首页 » 编程设计

python之将变量从在树莓派上运行的 python 脚本发送到网络服务器

2025年02月15日7xing901022

我有一个在我的树莓派上运行的 python 脚本,它从连接到树莓派的 GPIO 输入的传感器输出数据。我需要一种简单的方法来从任何地方访问服务器上的实时数据。我看过 django 框架,但对于我需要做的事情来说似乎有点过分了。

请您参考如下方法:

你的意思是像this?

你可以像这样用一些 JS 创建一个静态网页:

<html> 
<head> 
    <title>My Pi</title> 
    <script 
      src="https://code.jquery.com/jquery-3.2.1.min.js" 
      integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" 
      crossorigin="anonymous"></script> 
</head> 
<body> 
    <div id="sensor1"></div> 
    <a href="javascript:getSensor1()">Get data from sensor 1</a> 
    <script type="text/javascript"> 
        function getSensor1() { 
            $.ajax({ 
                type: "POST", 
                url: "cgi-bin/cputemp.py", 
                dataType: "html", 
                success: function(msg) { 
                    document.getElementById('sensor1').innerHTML = msg; 
                }, 
            }); 
        } 
    </script> 
</body> 

在相对于您的 html 页面的 cgi-bin/cputemp.py 目录中还有类似的内容。

#!/usr/bin/python 
import cgi; 
import cgitb; 
import time 
cgitb.enable() 
import commands 
import sys 
import string 
print "Content-type: text/html\n\n"; 
mytemp1 = commands.getoutput('/opt/vc/bin/vcgencmd measure_temp | cut -d "=" -f2 | cut -f1') 
output = "Pi CPU Temp is: " + mytemp1 
print output