javascript - 在 javascript 中使用 python 输出
问题描述
我们想将一个布尔值从 python 发送到 javascript,以便我们可以在我们的 html 网站中使用它。
我们尝试使用套接字,但这对我们来说太复杂了。我们的下一个想法是使用 api,我们知道如何使用 javascript 从 api 获取信息。我们要做的是将python布尔值发布到api,然后使用javascript从api中获取布尔值。但我们不知道该怎么做。
我们为所有代码使用树莓派,并在按下时在 python 中返回 true 的硬件按钮。
但是这段代码对我们不起作用。我们也在使用pycharm作为我们的工作空间,这是一个问题吗?
我们当前的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()
我们用于测试的python代码:
import random
import json
import time
button_status = False
path = (r"C:\Users\Sam\Desktop\pythonProject\pythonflask\emplates") # 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)
解决方案
网页中的 Javascript 不能直接在您的计算机上运行 Python 脚本或从本地终端读取信息。您可以做的是让您的 Python 程序将一个小的 json 文件输出到您的 localhost 文件夹,当按下或释放按钮时,该文件夹会被覆盖,如下所示:
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
然后在您的 javascript 中,设置一个间隔以定期调用一个获取此 json 文件的函数,并根据该值(如果它已更改)执行某些操作:
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
当您的本地服务器更新文件时,可能会有一些延迟。
推荐阅读
- c++ - 如何将 std::function 或函数指针传递给 qtconnect?
- c# - Capture Audio on PC as a stream in real-time
- react-native - 在应用容器之间进行本机导航
- reactjs - 将巨大的选项列表导入主组件
- c++ - 数组不可分配
- python - 在seaborn中更改boxenplot中线的宽度
- python - 根据另一列从熊猫数据框中一列中的每个列表中删除元素
- string - 如何在golang中椭圆截断文本?
- django - Django rest 框架端点和传递值
- excel - 使用 Visual Basic 更新 Excel 标头