如何在NodeJS中使用Spawn将数据从子进程发送回父进程

nmpmafwu  于 2022-12-26  发布在  Node.js
关注(0)|答案(2)|浏览(230)

我尝试使用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
cclgggtu

cclgggtu1#

如果你不需要异步派生Python进程,那么你可以使用spawnSync代替spawn来直接获取一个包含stdoutstderr的对象作为字符串:

const { spawnSync } = require('child_process');
const python = spawnSync('python3', ['-c', `print("hello"); assert False`], { encoding: "utf8" });

// Access stdout
console.log(python.stdout)

// Access stderr
console.log(python.stderr)
vhmi4jdf

vhmi4jdf2#

我想到了,我把所有的产卵程序都打包进了Promise

// child.js

function run_python_script(jsonString){

    const promise = new Promise((resolve, reject) => {
    
        // 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()
        })

        python.stderr.on('data', (data)=>{
            console.log(`stderr: ${data}`)
            reject(new Error(`stderr occured`))
        })

        python.on('close', (code)=>{
            if (code !=0){
                reject(new Error(`error code: ${code}`))
            }else{
                resolve(dataToSend)
            }
        })
    })

    return promise
}

module.exports = { run_python_script };

================================================================这里是调用上述子函数的父函数:

//Parent.js

const Child = require('./Child.js');

var data = {
    "industry": "Financial Services",
    "revenue": 12345678
}

var jsonString = JSON.stringify(data);

var result = ''
Child.run_python_script(jsonString).then(returnedData => {
    var result = returnedData;
    console.log(result)
})
.catch(err => {
    console.log(err)
})

相关问题