python - 尝试从python-shell获取数据,将其解析为nodeJS中的对象

标签 python node.js electron

我在nodeJS和Python之间进行通讯时遇到了一些麻烦。
但是,结果不存储。而是在运行 shell 程序之前打印结果。为什么是这样?如何将python输出存储到对象?
在py脚本中编写一个临时JSON文件会更好吗?
这是我的代码:

var pyshell =  require('python-shell');

var result;

  pyshell.PythonShell.run('suggestionWSong.py', null, function  (err, results)  {
    if  (err)  throw err;
    console.log('hello.py finished.');
    console.log(results[0]);
    result = results[0];
    console.log(result);
  });
  console.log("AA");
  console.log(result);

这是我的输出:
AA
undefined
hello.py finished.
{'songs': [{'songName': 'song1New', 'author': 'auth1', 'features': {'bpm': 100, 'key': 'A', 'scale': 'Minor'}}, {'songName': 'song2New', 'author': 'auth2', 'features': {'bpm': 200, 'key': 'B', 'scale': 'Major'}}, {'songName': 'song3New', 'author': 'auth3', 'features': {'bpm': 300, 'key': 'C', 'scale': 'Minor'}}]}       
{'songs': [{'songName': 'song1New', 'author': 'auth1', 'features': {'bpm': 100, 'key': 'A', 'scale': 'Minor'}}, {'songName': 'song2New', 'author': 'auth2', 'features': {'bpm': 200, 'key': 'B', 'scale': 'Major'}}, {'songName': 'song3New', 'author': 'auth3', 'features': {'bpm': 300, 'key': 'C', 'scale': 'Minor'}}]} 
最终,我想做的是在一个 Electron 应用程序Python中拥有一个TS函数。我使用tsc将TS编译为JS,然后在Electron上运行。我不确定是否应该将结果发送回我的TS类,还是写一个可以根据需要读取的JSON文件。该信息将是歌曲库数据,因此我希望有5-10首歌曲及其功能。

最佳答案

pyshell.PythonShell.run是一个异步函数。
这意味着执行需要时间,因此您的脚本将在其下执行任何代码,而无需等待它
所以就像这样做

var pyshell =  require('python-shell');

var result;
console.log("AA");
console.log(result);

  pyshell.PythonShell.run('suggestionWSong.py', null, function  (err, results)  {
    if  (err)  throw err;
    console.log('hello.py finished.');
    console.log(results[0]);
    result = results[0];
    console.log(result);
  });

您需要告诉脚本等待函数执行
或在回调函数中运行所需的任何内容,但请注意不要落在Callback Hell
看看Promise或async await语法
您需要执行以下操作:
var pyshell =  require('python-shell');

var result;




let myPromise = new Promise((reject, resolve)=>{

pyshell.PythonShell.run('suggestionWSong.py', null, function  (err, results)  {
    if  (err)  reject(err);
    else {
      console.log('hello.py finished.');
      resolve(results);
}
 });

});
  
result = await myPromise
console.log("AA");
console.log(result);

注意:通常,您需要一个异步函数来使用await,但是在最新版本的 Node 中,您可以像我一样使用它

关于python - 尝试从python-shell获取数据,将其解析为nodeJS中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65988913/

相关文章:

node.js - Socket.io 中的双连接

node.js - 服务总线错误: The messaging entity

electron - 单击 Electron 自动更新

python - 统一码编码错误 : 'ascii' codec can't encode character u'\u2019' in position 47: ordinal not in range(128)

python - 如何将 Pandas Dataframe 转换为单个列表

mysql - 如何在 Sequelize 中正确设置自定义 'through' 表?

javascript - 如何暂停 Node.js 应用程序直到附加调试器

javascript - 未从输入元素获取输入的数据

python - 如何将 AsyncIterable 转换为 asyncio Task

python - 无需重新排列内存的 3×n 数组的紧凑规范