繁体   English   中英

使用鳗鱼将数据从python存储到Javascript中的变量

[英]Storing data from python to a variable in Javascript using eel

我正在使用 eel 制作一个小应用程序,该应用程序的部分功能要求它从文本文件中读取数据并将其作为变量存储在 javascript 中。我遇到的问题是,当我尝试将文本分配给变量时,一旦离开 eel 调用的 scope,变量就变空了。

这是一个例子:

主程序

@eel.expose
def ReturnTextString(train):
    
    # Create the data file path using the train param
    file = "data/{}.txt".format(train)

    # Store data to string
    dataFile = open(file, "r")
    moduleInfo = dataFile.read()
    dataFile.close()
    
    return moduleInfo

脚本.js

// Initialize the variable that will hold the data being read
var newData = "";

// Function that will assign what has been returned from python to our variable "newData"
async function assign(){
  newData = await eel.ReturnTextString("ps1")();
  console.log(newData); // <--- This console.log correctly prints the data from the text document
}

// Literally just print newData
function printCorrectly(){
  console.log(newData); // <--- This console.log prints an empty line
}

// Ideally, this call would assign our text to "newData"
assign();
// And then this would confirm that it survived leaving the scope of assign()
printCorrectly();
// But it does not :(

这似乎是一个 scope 问题,但让我陷入循环的是“newData”是一个全局变量,当程序退出分配 function 的 scope 时它似乎失去了它的价值。我对鳗鱼,因为这是我第一次使用它。 如果有人可以解释发生了什么以及任何可能的解决方案,那将是惊人的,谢谢!

assign()会将全局变量 newData 更改为“来自文本文档的数据”,但是在调用printCorrectly()时,由于超时,承诺尚未解决,即使您立即解决 promise 它仍然只会改变它在printCorrectly()运行之后,因为 promise 将作为Microtask排队。

您可以简单地等待 assign() 先完成,然后像这样打印数据:

assign().then(() => printCorrectly())

或者您添加一个 setTimeout 来等待分配或一个 setInterval 来检查它何时发生(尽管不推荐)。

setTimeout(() => printCorrectly(), 0); setTimeout(() => printCorrectly(), 1000);

暂无
暂无

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

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