Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return result from python script in Node JS child process

Tags:

node.js

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;
        })();
like image 973
AdamA Avatar asked Oct 24 '25 01:10

AdamA


2 Answers

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")
like image 154
Naor Tedgi Avatar answered Oct 26 '25 16:10

Naor Tedgi


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()
like image 32
kg99 Avatar answered Oct 26 '25 17:10

kg99



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!