How to call a Python function from Node.js

前端 未结 9 1642
借酒劲吻你
借酒劲吻你 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条回答
  •  猫巷女王i
    2020-11-22 15:18

    The python-shell module by extrabacon is a simple way to run Python scripts from Node.js with basic, but efficient inter-process communication and better error handling.

    Installation: npm install python-shell.

    Running a simple Python script:

    var PythonShell = require('python-shell');
    
    PythonShell.run('my_script.py', function (err) {
      if (err) throw err;
      console.log('finished');
    });
    

    Running a Python script with arguments and options:

    var PythonShell = require('python-shell');
    
    var options = {
      mode: 'text',
      pythonPath: 'path/to/python',
      pythonOptions: ['-u'],
      scriptPath: 'path/to/my/scripts',
      args: ['value1', 'value2', 'value3']
    };
    
    PythonShell.run('my_script.py', options, function (err, results) {
      if (err) 
        throw err;
      // Results is an array consisting of messages collected during execution
      console.log('results: %j', results);
    });
    

    For the full documentation and source code, check out https://github.com/extrabacon/python-shell

提交回复
热议问题