简体   繁体   中英

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.

For example, once the button is pressed some boolean will turn true, we will call the boolean bool_1. Then that boolean is sent to my python code, or written to a text file. Then in my python code I want to do something depending on that value. 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. My python code is constantly running, computing live values from sensors.

The easiest way I can think of is to run a web server, maybe something simple like Flask . If the python script is running on your machine, you should run flask on your machine as well. 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.).

it's a web page, why don't you use php code? 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:

<?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.

Maybe you can try to create a nodejs script that create a websocket. 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.

Have a nice day

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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