通过NodeJS执行Python

时间:2017-09-13 19:06:23

标签: python node.js

目的:
从现有的NodeJS api

执行python机器学习模型

到目前为止:
我写了一个小班来处理产卵并保持儿童过程活着 我可以启动,执行和返回python进程的结果,但它看起来很奇怪。经过一些分析后,我发现了<在python代码中花费了18ms,但是从调用execute()callback(result)的时间是> 500毫秒。

end事件需要很长时间才能解雇吗?任何建议都有帮助!

类别:

const spawn = require('child_process').spawn;

class PythonRunner {
    constructor(opts) {
        this.py = {};
        this.script = opts[0].script;
        this.py.process = spawn('python', [opts[0].script]);
    }


    /*
    time leak in execute is between write and .on(data);
    */

    execute(args, callback) {
        console.time('execute');
        args = JSON.stringify(args);
        let result = '';
        this.py.process.stdout.on('data', (data) => {
            // console.log(data.toString());
            result += data.toString();
        });
        this.py.process.stdout.on('end', () => {
            console.timeEnd('execute');
            this.py.process = spawn('python', [this.script]);
            callback(result)
        });
        this.py.process.stdin.write(`${args}`);
        this.py.process.stdin.end();
    }
}

module.exports = PythonRunner;

执行代码:

let Runner = require('../index');


let args = [8, 6, 22.92, 144.163, 3, 22.92, 498.562, 130.6713, -25.457, -26.1477, 22.92, 54, 101.166666666667, 4.52941176470588, 19.1995473684211, 23.81, -27.2147, 2.424, 2.472, 2.389]
let options = [
    { name: 'somePythonModel', script: './__pycache__/SOME_PYTHON_MODEL.cpython-36.pyc', args: args }
];


let script = new Runner(options);

(function executeAgain() {
    script.execute(args, (res) => {
        console.log(res);
        executeAgain();
    });
})();

来自时间分析的结果:(read_in(),model_score()和main()都在python代码中)

execute: 538.514ms
read_in(): 0.030994ms
model_score(): 17.854929ms
main(): 17.935991ms

execute: 539.759ms
read_in(): 0.027895ms
model_score(): 18.370152ms
main(): 18.446922ms

execute: 545.662ms
read_in(): 0.030994ms
model_score(): 18.548965ms
main(): 18.632889ms

0 个答案:

没有答案