0

I am trying the following code to get desired python output and store it and also send the result as http response from Node.js. Here is my code

This the the python test.py file

import sys

print("Output from Python")
print("First name: " + sys.argv[1])
print("Last name: " + sys.argv[2])

This is Node.js spawn methods

testRoute: async(req, res, next) => {

var output="";

var child = spawn('python', [`${process.cwd()}/pyCodes/test.py`,
   'Itachi',
   'Uchiha'
 ]);

child.stdout.setEncoding('utf8');
await child.stdout.on('data', (data) => {
   data = data.toString();
   output += data;
});

 child.stderr.on("data", (data) => {
    data = data.toString();
    output += data;
  });

child.on("error", (error) => {
  error = error.toString();
  output += error;
});

 child.stderr.pipe(process.stderr);

 cosnsole.log('output: ', output) // this shows output as empty
 
child.on("close", (code) => {
   return res.send({
        statusCode: 200,
        status: 'Success',
        data: output, // the output is like this : "Output from Python\r\nFirst name: Itachi\r\nLast name: Uchiha\r\n"
      });
 });
}

But the output only prints in console/ insides spawn methods. If I access the output from outside spawn methods it shows empty. How can I store the output from python code in some variable? Also if I directly do res.send() inside child.on('close') the resultant string contains special characters like '\r','\n' etc... how can i avoid that? I even tried using JSON.parse but it throws error finding unwanted token at position 0 . Please if anyone can let me know how to get proper output in res.send() and also how to store output in variable even as JSON?

2 Answers 2

1
+50

I don't think so there are any such ways to do it. All you can do it pass the result of python code which u get from spawn to another route or return it via http response or pass it to another function.

Sign up to request clarification or add additional context in comments.

Comments

0

But the output only prints in console/ insides spawn methods. If I access the output from outside spawn methods it shows empty. How can I store the output from python code in some variable?

You can't. As spawn methods are running asynchronously. It's expected to print or play with data once a close event trigger is received. So your code must be aligned to the behavior.

child.on("close", (code) => {
   console.log("output") 
}

Also if I directly do res.send() inside child.on('close') the resultant string contains special characters like '\r','\n' etc... how can i avoid that

You can use a regex to remove special/escape characters from your final string. example

child.on("close", (code) => {
   output = output.replace(/\\"/g, '"');  //somewhat like regex ?

   return res.send({
        statusCode: 200,
        status: 'Success',
        data: output
      });
 });
}

2 Comments

so isn't there any other way to store output in variables from python code apart from spawn?
Do you need to run python "localy"? You can make it as server with a framework (for example flask) and make your node.js API communicate with python with REST (send and receive JSON) .

Your Answer

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