How to call a Python function from Node.js

前端 未结 9 1627
借酒劲吻你
借酒劲吻你 2020-11-22 14:53

I have an Express Node.js application, but I also have a machine learning algorithm to use in Python. Is there a way I can call Python functions from my Node.js application

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 15:06

    Most of previous answers call the success of the promise in the on("data"), it is not the proper way to do it because if you receive a lot of data you will only get the first part. Instead you have to do it on the end event.

    const { spawn } = require('child_process');
    const pythonDir = (__dirname + "/../pythonCode/"); // Path of python script folder
    const python = pythonDir + "pythonEnv/bin/python"; // Path of the Python interpreter
    
    /** remove warning that you don't care about */
    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 result = "";
            let resultError = "";
            pyprog.stdout.on('data', function(data) {
                result += data.toString();
            });
    
            pyprog.stderr.on('data', (data) => {
                resultError += cleanWarning(data.toString());
            });
    
            pyprog.stdout.on("end", function(){
                if(resultError == "") {
                    success(JSON.parse(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;
    

    Call:

    const pythonCaller = require("../core/pythonCaller");
    const result = await pythonCaller.callPython("preprocessorSentiment.py", {"thekeyYouwant": value});
    

    python:

    try:
        argu = json.loads(sys.argv[1])
    except:
        raise Exception("error while loading argument")
    

提交回复
热议问题