节点:等待python脚本运行

我有以下代码。 我在哪里上传文件,然后我读取文件和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', }); }); 

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

要在一些asynchronous操作之后返回结果,应该在done-callback中调用res.send

 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', }); }); }); 

那么如果你不能在控制台中看到日志(*),那么这将意味着脚本不能正常工作或工作不正常。 callback没有被调用。 首先,您需要确保脚本(PythonShell.run)能够正常工作,并且正在调用callback。 POST处理程序将等待,直到您调用res.send (无论延迟值),以便callback是主要的点。

另外readFileSync可能会失败。 在readFileSync失败的情况下,你应该会看到一个exception。 如果没关系,那么你会看到下一个日志(**)和响应将被发送。


我在你的代码中看到了PythonShell 。 我没有经验,但经过一番阅读,我认为这个问题可能在于你如何使用它。 它似乎是python-shell npm包,所以下面的文档可以尝试为脚本实例化一个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' }); } }); }); 

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

  • 脚本的path
  • 参数
  • 其他设置

尝试删除所有参数(创build一些新的testing脚本),清理设置对象(只保留path),并从节点执行它。 在Node中处理结果。 你应该能够通过正确的path运行最简单的脚本! 研究如何设置正确的scriptPath 。 然后向你的脚本添加一个参数,并用参数运行它。 再次得到结果。 没有太多的select ,但他们每个人都可能是不正确的呼叫的原因。