节点:等待python脚本运行

Gam*_*mer 3 javascript python asynchronous node.js express

我有以下代码。我首先上传文件,然后读取文件和console输出,如console.log(obj). 但是响应是第一位的,python 脚本在幕后运行。我怎样才能让代码等待 python 脚本运行然后继续?

router.post(`${basePath}/file`, (req, res) => {

    //Upload file first

    PythonShell.run('calculations.py', { scriptPath: '/Path/to/python/script' }, function (err) {
        console.log(err);
        let obj = fs.readFileSync('Path/to/file', 'utf8');
        console.log(obj);
    });

    return res.status(200).send({
        message : 'Success',
    });
});
Run Code Online (Sandbox Code Playgroud)

我无法获得console.log(obj);输出,因为它在响应之后运行。我怎样才能让它等待 python 脚本运行并console.log(obj)在控制台上获得输出。

dhi*_*ilt 5

要在一些异步操作后返回结果,您应该res.send在 done-callback 内部调用。

router.post(`${basePath}/file`, (req, res) => {

    //Upload file first

    PythonShell.run('calculations.py', { scriptPath: '/Path/to/python/script' }, function (err) {
        console.log('The script work has been finished.'); // (*)
        if(err) {
          res.status(500).send({
            error: err,
          });
          console.log(err);
          return;
        }
        let obj = fs.readFileSync('Path/to/file', 'utf8');
        console.log(obj); // (**)
        res.status(200).send({
            message : 'Success',
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

然后,如果您不会在控制台中看到日志 (*),则表示该脚本无法正常工作或无法正常工作。没有调用回调。首先,您需要确保脚本 (PythonShell.run) 工作正常并且正在调用回调。POST 处理程序将等到您调用res.send(无论延迟值如何),因此回调是重点。

readFileSync 也可能失败。如果 readFileSync 失败,您应该会看到异常。如果没问题,那么您将看到下一个日志 (**) 并发送响应。


PythonShell在你的代码中看到了。我没有这方面的经验,但经过一些阅读后,我认为问题可能出在您使用它的方式上。看起来是python-shellnpm 包,所以按照它的文档,你可以尝试为你的脚本实例化一个 python shell,然后使用侦听器:

let pyshell = new PythonShell('calculations.py');

router.post(`${basePath}/file`, (req, res) => {
  pyshell.send(settings); // path, args etc
  pyshell.end(function (err) {
    console.log('The script work has been finished.');
    if(err) { res.status(200).send({ error: err }); }
    else { res.status(200).send({ message : 'Success' }); }
  });
});
Run Code Online (Sandbox Code Playgroud)

这种方法可能更合适,因为 pyton shell 在不同的 POST 请求之间保持打开状态。这取决于您的需求。但我猜它并没有解决脚本运行的问题。如果您确定脚本本身没有问题,那么您只需要在 Node 环境中正确运行它即可。有几点:

  • 脚本路径
  • 争论
  • 其他设置

尝试删除所有参数(创建一些新的测试脚本),清理设置对象(仅保留路径)并从 Node.js 执行它。在 Node.js 中处理它的结果。您应该能够通过正确的路径运行最简单的脚本!研究如何正确设置scriptPath。然后向您的脚本添加一个参数并使用参数运行它。再次处理结果。没有那么多选项,但每一个选项都可能是调用不当的原因。