【问题标题】:Execute Python script from Node.js and wait for termination从 Node.js 执行 Python 脚本并等待终止
【发布时间】:2021-03-08 03:02:12
【问题描述】:

我正在使用 Node.js 构建一个 API-Rest,需要执行一个 python 脚本,该脚本将生成一个 .json 文件并将其保存在一个目录中。因此,我想等待 python 程序终止,以便节点可以使用输出 JSON 文件。这是我实现的代码 How to call a Python function from Node.js

const { spawn } = require('child_process');
const pythonDir = (__dirname + "./"); // Path of python script folder
const python = pythonDir + "./env/Scripts/python"; // Path of the Python interpreter

function cleanWarning(error) {
    return error.replace(/Detector is not able to detect the language reliably.\n/g,"");
}

function callPython(scriptName, args) {
    return new Promise(function(success, reject) {
        const script = pythonDir + scriptName;
        const pyArgs = [script, JSON.stringify(args) ]
        const pyprog = spawn(python, pyArgs );
        let resultError = "";
    
        pyprog.stderr.on('data', (data) => {
            resultError += cleanWarning(data.toString());
        });

        pyprog.stdout.on("end", function(){
            if(resultError == "") {
                var result = require('./optimalRoute.json')
                success(result);
            }else{
                console.error(`Python error, you can reproduce the error with: \n${python} ${script} ${pyArgs.join(" ")}`);
                const error = new Error(resultError);
                console.error(error);
                reject(resultError);
            }
        })
   });
}
module.exports.callPython = callPython;

调用函数:

...
route: async function(req, res){
        const pythonCaller = require("../models/routeGeneration");
        const locaciones = require("../models/example");
        const  result = await pythonCaller.callPython("CVRP.py", {"delivery":locations});
    }
...

认为这不起作用,因为我永远处于待处理状态,有人可以帮助我吗?谢谢

Promise { <pending> }

【问题讨论】:

  • 你试过pyprog.on('close',...)pyprog.on('exit',...)吗?这里的文档nodejs.org/api/…

标签: javascript python node.js promise


【解决方案1】:

我同意@Molda。我假设stdout.on("end") 在这种情况下适用于EOF。如果它完全发出。 process.stdoutnet.Socket 所以 Socket.on('end') 是我找到的最接近的适用信息。这确实暗示了我在net 上下文中所做的相同假设。我找不到更具体的内容。

【讨论】:

    猜你喜欢
    • 2016-09-13
    • 2019-09-16
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 2017-12-27
    相关资源
    最近更新 更多