Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJs: Get output of python-shell to send back to client

Tags:

python

node.js

I am trying to create a website where a user can submit python code, it gets sent to my server to be executed and I send back the results to the client. Currently I am using a NodeJs server and need to run the python code from there. To do this, I am using Python-shell like so:

const runPy = async (code) => {
   const options = {
      mode: 'text',
      pythonOptions: ['-u'],
      scriptPath: path.join(__dirname, '../'),
      args: [code],
   };

  const result = await PythonShell.run('script.py', options, (err, results) => {
     if (err) throw err;
     return results; <----- HOW DO I RETURN THIS
  });
  console.log(result.stdout);
  return result;
};

I understand I can console.log() the results in the PythonShell.run() but is there a way to return the results from my runPy function to then be manipulated and sent back to the client?

like image 252
user081608 Avatar asked Dec 05 '25 16:12

user081608


1 Answers

It looks from the python-shell documentation that the PythonShell.run method doesn't have an async mode. So, one option is to wrap it in a promise:

const runPy = async (code) => {
   const options = {
      mode: 'text',
      pythonOptions: ['-u'],
      scriptPath: path.join(__dirname, '../'),
      args: [code],
   };

  // wrap it in a promise, and `await` the result
  const result = await new Promise((resolve, reject) => {
    PythonShell.run('script.py', options, (err, results) => {
      if (err) return reject(err);
      return resolve(results);
    });
  });
  console.log(result.stdout);
  return result;
};
like image 53
jknotek Avatar answered Dec 07 '25 06:12

jknotek



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!