Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

Using a python output in javascript

We want to send a boolean value from python to javascript so we can use it in our html website.

We tried using sockets but thats too complicated for us. Our next thought was to use an api and we know how to get information from an api using javascript. What we want to do is post a python boolean value to an api, and then get the boolean value from the api using javascript. But we don't know how to do so.

We are using a raspberry pi for all our code and a hardware-button which returns true in python when pressed.

We are currently testing code we found from https://healeycodes.com/javascript/python/beginners/webdev/2019/04/11/talking-between-languages.html

But this code doesnt work for us. We are also using pycharm as our workspace, is this a problem?

Our current code in javascript:

    const request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
        if (request.readyState === 4 && request.status === 200) {
            success(JSON.parse(request.responseText));
        }
    };
    request.send();
     setInterval(get("button-status.json", receiveStatus), 3000);
}


function receiveStatus(response) {
    if (response.status !== status) {  // only do something if status has changed
        status = response.status;
        console.log('button status is now', status);
    }
}
let status;
// checks every 100ms
get()

Our python code we're using for testing:

import random
import json
import time
button_status = False
path = (r"C:UsersSamDesktoppythonProjectpythonflaskemplates")  # replace with your actual path

def save_button_status():
    with open(path + "/button-status.json", "w") as f:
        json.dump({'status': button_status}, f)



while True :
    value = random.randrange(1, 10)
    if ( value <= 5) :
        button_status = True
        save_button_status()
        time.sleep(3)
    else :
        button_status = False
        save_button_status()
        time.sleep(3)

    print(button_status)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Javascript within a webpage cannot directly run a Python script on your computer or read information from a local terminal. What you could do is have your Python program output a small json file to your localhost folder which is overwritten when the button is pressed or released, like this:

import json
button_status = False   # assuming it is initially off
path = "path/to/your/localhost/folder"  # replace with your actual path

def save_button_status():
    with open(path + "/button-status.json", "w") as f:
        json.dump({'status': button_status}, f)

# Then call save_button_status() whenever the status changes

Then in your javascript, set an interval to periodically call a function that gets this json file and does something based on the value if it has changed:

function get(url, success) {
    //--- Get JSON data at the given URL and call `success` if successful
    const request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
        if (request.readyState === 4 && request.status === 200) {
            success(JSON.parse(request.responseText));
        }   
    };
    request.send();
}

function receiveStatus(response) {
    if (response.status !== status) {  // only do something if status has changed
        status = response.status;
        console.log('button status is now', status);
    }
}
let status;
let interval = setInterval(() => get("button-status.json", receiveStatus), 100); // checks every 100ms

There may be some lag as your local server updates the file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...