简体   繁体   English

在树莓派上的HTML和python之间发送消息

[英]Sending a message between HTML and python on the raspberry pi

I want to do the following. 我要执行以下操作。 I want to have a button on a HTML page that once It gets pressed a message is sent to some python script I'm running. 我想在HTML页面上有一个按钮,一旦按下该按钮,就会向我正在运行的某些python脚本发送一条消息。

For example, once the button is pressed some boolean will turn true, we will call the boolean bool_1. 例如,一旦按下按钮,一些布尔值将变为true,我们将其称为布尔值bool_1。 Then that boolean is sent to my python code, or written to a text file. 然后,该布尔值将发送到我的python代码,或写入文本文件。 Then in my python code I want to do something depending on that value. 然后在我的python代码中,我想根据该值做一些事情。 Is there a way to do this? 有没有办法做到这一点? Ive been looking at many thing but they haven't worked. 我一直在看很多东西,但是他们没有用。 I know that in javascript you can't write a text files because of security issues. 我知道在javascript中由于安全问题您无法编写文本文件。 My python code is constantly running, computing live values from sensors. 我的python代码不断运行,从传感器计算实时值。

The easiest way I can think of is to run a web server, maybe something simple like Flask . 我能想到的最简单的方法是运行Web服务器,例如Flask If the python script is running on your machine, you should run flask on your machine as well. 如果您的计算机上正在运行python脚本,则也应在计算机上运行flask。 The flask backend will receive the button press, and you can either put your sensor reading code inside one of the web server handlers, or you can choose some other method for your webserver to communicate with the running script (eg. sockets, text files, etc.). 烧瓶后端将按一下按钮,您可以将传感器读取代码放入一个Web服务器处理程序中,也可以选择其他方法让Web服务器与正在运行的脚本进行通信(例如套接字,文本文件,等等。)。

it's a web page, why don't you use php code? 这是一个网页,为什么不使用php代码? from index.php you can write your data on a txt file by pressing an html button (form or ajax code), sending everything you want with GET or POST and read it in the same file or in a -receiver.php- with: 在index.php中,您可以通过按html按钮(表单或ajax代码),使用GET或POST发送您想要的所有内容,然后在同一文件或-receiver.php-中使用以下命令将数据写入txt文件中:

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = $_REQUEST['get_or_post_var'];
fwrite($myfile, $txt);
fclose($myfile);
?>

Your python code can read it line by line with readlines() function. 您的python代码可以使用readlines()函数逐行读取它。

Maybe you can try to create a nodejs script that create a websocket. 也许您可以尝试创建一个创建websocket的nodejs脚本。 You ca connect to the websocket with python and so, you are able to send data from your website to nodejs and from nodejs to python in real-time. 您可以使用python连接到网络套接字,因此,您可以将数据从您的网站实时发送到nodejs,也可以将数据从nodejs实时发送到python。

Have a nice day 祝你今天愉快

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM