4

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;
        })();
11
  • Can you also post your python script. What are you returning from python and how? Commented Nov 28, 2020 at 20:22
  • @kg99 for now just printing hello 'name' , trying to understand how this works Commented Nov 28, 2020 at 20:27
  • Then your code should work. just test with only print "hello" in your python script. The buffer should collect the output data. just call it like const childPython = spawn('python' ,['main.py']);. I think you are doing something wrong in your script. Commented Nov 28, 2020 at 20:34
  • @kg99 it works fine, but it only prints the result in the console, i would like to send that result into a variable to use somewhere else in my code Commented Nov 28, 2020 at 20:39
  • Your already stored it in results. Can you add console.log(results). Commented Nov 28, 2020 at 20:42

2 Answers 2

3
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")
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

So if i want to manipulate the string playList would i just set a variable = to the runTest() and manipulate that?
yes. you can do anything with the variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.