我尝试使用spawn子进程从NodeJS运行python脚本。我能够成功地让python运行并使用控制台日志查看数据,但无法将实际数据发送回父函数,以便在其他地方使用它。
这是在Node.js中调用spawn的“Child.js”文件:
//Child.js: Node.js file that executes a python script using spawn...
function run_python_script(jsonString, callback){
//spawn new child process to call the python script
const {spawn} = require('child_process');
const python = spawn('python3', ["-c",`from apps import python_app; python_app.run(${jsonString});`]);
var dataToSend = ''
python.stdout.on('data', (data) => {
dataToSend = data.toString() //<---How do I return this back to other functions?
return callback(dataToSend) //<---this is not returning back to other functions.
})
python.stderr.on('data', (data)=>{
console.log(`stderr: ${data}`)
})
}
module.exports = { run_python_script };
====================================================这是调用“Child.js”文件的文件,在上面我想从Python接收数据...
const Child = require('./Child.js');
const callback = (x)=>{return x} //<--simply returns what's put in
let company_data = {
"industry": "Financial Services",
"revenue": 123456789
}
jsonString = JSON.stringify(company_data);
let result = ''
result = Child.run_python_script(jsonString, callback) //<-- I want the results from python to be stored here so I can use it elsewhere.
console.log(result) //<--this returns "undefined". Data isn't coming back
2条答案
按热度按时间cclgggtu1#
如果你不需要异步派生Python进程,那么你可以使用
spawnSync
代替spawn
来直接获取一个包含stdout
和stderr
的对象作为字符串:vhmi4jdf2#
我想到了,我把所有的产卵程序都打包进了Promise
================================================================这里是调用上述子函数的父函数: