简体   繁体   中英

Return result from python script in Node JS child process

Im trying to return the value from a python script from a nodejs child process and i just cant seem to get it to work, it prints in the console using console.log correctly as it should but only returns undefined, i was wondering if there is a way to directly return that value, or to parse the console.log results into a string.

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 script is empty for now and prints "Hello 'name' " Edit: I tried to use promises and here is what i have:

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

Define it like this.

 function getPlaylist(name) {
      return new Promise((resolve , reject) => {
          const childPython = spawn('python' ,['main.py', name]);
          var result = '';
          childPython.stdout.on(`data` , (data) => {
              result += data.toString();
          });
      
          childPython.on('close' , function(code) {
              resolve(result)
          });
          childPython.on('error' , function(err){
              reject(err)
          });
  
      })
    };

Remeber to use try...catch for it it gets rejected. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch

async function runTest() {
  try {
    const playList = await getPlaylist();
    console.log(playList);
  } catch (err) {

  }
}
 
runTest()
const {spawn} = require('child_process');

const getPythonScriptStdout = (pythonScriptPath) => {
    const python = spawn('python', [pythonScriptPath]);
    return new Promise((resolve, reject) => {
        let result = ""
        python.stdout.on('data', (data) => {
            result += data
        });
        python.on('close', () => {
            resolve(result)
        });
        python.on('error', (err) => {
            reject(err)
        });
    })
}


getPythonScriptStdout('./python.py').then((output) => {
    console.log(output)
})

python.py file

print("hi from python")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM