nad
nad

Reputation: 2850

Call a Python function from NodeJS

I need to call a python function from a NodeJS service code. I checked this link and wrote below nodeJS code

const express = require('express')
const app = express()

let runPy = new Promise(function(success, nosuccess) {

    const { spawn } = require('child_process');
    const pyprog = spawn('python', ['./ml.py']);

    pyprog.stdout.on('data', function(data) {

        success(data);
    });

    pyprog.stderr.on('data', (data) => {

        nosuccess(data);
    });
});

app.get('/', (req, res) => {

    res.write('welcome\n');

    runPy.then(function(testMLFunction) {
        console.log(testMLFunction.toString());
        res.end(testMLFunction);
    });
})

app.listen(4000, () => console.log('Application listening on port 4000!'))

Suppose I have a sample python code in ml.py like below

def testMLFunction():
    return "hello from Python"

Now when I run the nodeJS code and do a GET through Curl, I only see the message 'welcome' which is the console log of GET endpoint. But I don't see the message that is returned from the python function anywhere. What am I missing?

Upvotes: 0

Views: 2383

Answers (1)

user10093237
user10093237

Reputation:

I guess you misunderstand the process of calling python. You are not calling python function in node directly but call the process to run a shell command that run ./ml.py and collect the console output.

If that's clear then the problem is obvious, you define the function in python but you forget to call it.

def testMLFunction():
    return "hello from Python"

print(testMLFunction())

By the way, I guess you are going to refer a machine learning algorithm as it is named as ML. If that's the case, calling it from shell may be inefficient as loading a model could be time consuming and it will be loaded whenever you call it.

Instead, I recommend you also build a python server, and access these predicted result via internal http request.

Upvotes: 6

Related Questions