3

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?

1 Answer 1

4

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

Comments

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.