NodeJs:获取python-shell的输出并发送回客户端

3

我正在尝试创建一个网站,用户可以提交Python代码,它会被发送到我的服务器执行,然后将结果发送回客户端。目前我正在使用NodeJs服务器,并需要从那里运行Python代码。为此,我正在使用Python-shell,如下所示:

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;
};

我知道我可以在PythonShell.run()中使用console.log()来打印结果,但是有没有一种方法可以将我的runPy函数的结果返回,以便进行操作并发送回客户端?
1个回答

4

python-shell 文档中可以看出,PythonShell.run 方法没有异步模式。所以,一种方法是将其包装在一个 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;
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接