我在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/