【问题标题】:Call a Python function from NodeJS从 NodeJS 调用 Python 函数
【发布时间】:2018-12-25 18:20:32
【问题描述】:

我需要从 NodeJS 服务代码中调用 python 函数。我检查了this link并在nodeJS代码下面写了

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!'))

假设我在ml.py 中有一个示例 python 代码,如下所示

def testMLFunction():
    return "hello from Python"

现在,当我运行 nodeJS 代码并通过 Curl 执行 GET 时,我只看到消息 'welcome' 这是 GET 端点的控制台日志。但是我在任何地方都看不到从 python 函数返回的消息。我错过了什么?

【问题讨论】:

    标签: python node.js


    【解决方案1】:

    我猜你误解了调用python的过程。您不是直接调用node 中的python 函数,而是调用进程来运行运行./ml.py 的shell 命令并收集控制台输出。

    如果这很清楚,那么问题就很明显了,你在 python 中定义了函数但你忘记调用它。

    def testMLFunction():
        return "hello from Python"
    
    print(testMLFunction())
    

    顺便说一句,我猜你会提到一种机器学习算法,因为它被命名为 ML。 如果是这种情况,从 shell 调用它可能效率低下,因为加载模型可能很耗时,并且无论何时调用它都会被加载。

    相反,我建议您也构建一个 python 服务器,并通过内部 http 请求访问这些预测结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      • 2013-08-30
      相关资源
      最近更新 更多