【发布时间】:2020-11-28 20:18:10
【问题描述】:
我试图从 nodejs 子进程的 python 脚本返回值,但我似乎无法让它工作,它使用 console.log 在控制台中正确打印,但只返回未定义,我想知道如果有办法直接返回该值,或者将 console.log 结果解析为字符串。
var sys = require('util');
module.exports = function() {
this.getPlay = function getPlaylist(name) {
const childPython = spawn('python' ,['main.py', name]);
var result = '';
childPython.stdout.on(`data` , (data) => {
result += data.toString();
});
childPython.on('exit' , () => {
console.log(result);
});
}};
Python 脚本暂时为空,并打印“Hello 'name'” 编辑: 我尝试使用承诺,这就是我所拥有的:
(async function(){
function test(name) {
return new Promise((resolve , reject) => {
const childPython = spawn('python' ,['main.py', "He"]);
var result = '';
childPython.stdout.on(`data` , (data) => {
result += data.toString();
});
childPython.on('close' , function(code) {
t = result
resolve(result)
});
childPython.on('error' , function(err){
reject(err)
});
})};
var t;
await test(name);
console.log(t);
return t;
})();
【问题讨论】:
-
你也可以发布你的python脚本吗?你从 python 中返回了什么以及如何返回?
-
@kg99 现在只是打印 hello 'name' ,试图了解它是如何工作的
-
那么你的代码应该可以工作了。只需在您的 python 脚本中仅打印“hello”进行测试。缓冲区应该收集输出数据。只需将其称为 const childPython = spawn('python' ,['main.py']);。我认为您在脚本中做错了什么。
-
@kg99 它工作正常,但它只在控制台中打印结果,我想将该结果发送到一个变量中以在我的代码中的其他地方使用
-
您已将其存储在结果中。你能添加console.log(results)吗?
标签: node.js