首页 > 解决方案 > 尝试从 python-shell 获取数据,将其解析为 nodeJS 中的对象

问题描述

我在 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'}}]} 

最终我想要做的是在电子应用程序调用 Python 中有一个 TS 函数。我使用 tsc 将我的 TS 编译成 JS,然后在 Electron 上运行。我不确定是否应该将结果发送回我的 TS 类,或者编写一个我可以根据需要读取的 JSON 文件。此信息将是歌曲库数据,因此我预计 5-10 首歌曲及其特征。

标签: pythonnode.jselectron

解决方案


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);
  });

您需要告诉脚本等待函数执行或在回调函数中运行您想要的任何内容,但请注意不要陷入回调地狱

看看 promises 或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但在最新版本的节点中,您可以像我一样使用它


推荐阅读