Marcos Elric
Marcos Elric

Reputation: 1

Using python functions in html

First of all, I am not a native English speaker, so please forgive any spelling mistakes I may have.

I am trying to integrate HTML and Python to create a GUI that can "speak" to a bus (KNX bus if you are interested).

I have a raspberry pi with an HTML page and some Python scripts, that are the ones that actually talk to the bus. I have managed to run python scripts from HTML with a bit of PHP (I am not particularly proficient in PHP), doing something like this:

if (isset($_POST ['button'])){
   exec("sudo pathofpythonscript/pythonscript.py")
}

And it works just fine, when the button it's pressed, the script it's executed. But now, I want to have a script running (since I want python to be reading from the UART from the bus and display that information) and when something in the scripts happens (a condition it's met, for example), I want to be able to talk to the HTML to change a CSS property or anything else, something like this pseudo-code here

//This is just pseudo-code to try to illustrate my question, IT'S NOT working code
//In the python file, a simple toggle function
if bus_event
  var != var

//in Html, with javascript
if (var_from_python_script == true){
document.getElementById('button').style.background=red;
}

If someone could tell me just how to make a simple example, with something like a python script that toggles any boolean parameter that enters and returns it, and how to "grab" that return from javascript/HTML to use it,

I think I can work everything else.

Thank you in advance!

Upvotes: -1

Views: 584

Answers (1)

Eric Darchis
Eric Darchis

Reputation: 26647

You are confusing the HTML/CSS/Javascript code that is running in your browser and the (PHP/Python) code that is running on the server. Even if in your case, they might be the same, it doesn't matter. The python script is not running in your browser and therefore cannot change the state of your html/css or even javascript.

When you are executing your code with exec, the PHP server is running an external command and expecting a response to the immediate request. After that, it's over.

I would recommend to ditch PHP and use a Python web application framework. Flask, Django or whatever else. This will allow you to interact directly with the python code. Your web browser could then request data to your server and know what is happening. Remember, the web is normally only from the browser to the server.

Now, if you need real-time interactions, you should have a look at websockets. These will allow bidirectional communication between your browser and the running python app. There are a number of caveats with this technology but it might be better suited to your needs. Note that this will force you to write Javascript code in your browser to manage this communication but it shouldn't be too hard.

Upvotes: 0

Related Questions