How to call a Python function from Node.js

前端 未结 9 1484
借酒劲吻你
借酒劲吻你 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:22

    You could take your python, transpile it, and then call it as if it were javascript. I have done this succesfully for screeps and even got it to run in the browser a la brython.

    0 讨论(0)
  • 2020-11-22 15:23

    Example for people who are from Python background and want to integrate their machine learning model in the Node.js application:

    It uses the child_process core module:

    const express = require('express')
    const app = express()
    
    app.get('/', (req, res) => {
    
        const { spawn } = require('child_process');
        const pyProg = spawn('python', ['./../pypy.py']);
    
        pyProg.stdout.on('data', function(data) {
    
            console.log(data.toString());
            res.write(data);
            res.end('end');
        });
    })
    
    app.listen(4000, () => console.log('Application listening on port 4000!'))
    

    It doesn't require sys module in your Python script.

    Below is a more modular way of performing the task using Promise:

    const express = require('express')
    const app = express()
    
    let runPy = new Promise(function(success, nosuccess) {
    
        const { spawn } = require('child_process');
        const pyprog = spawn('python', ['./../pypy.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(fromRunpy) {
            console.log(fromRunpy.toString());
            res.end(fromRunpy);
        });
    })
    
    app.listen(4000, () => console.log('Application listening on port 4000!'))
    
    0 讨论(0)
  • 2020-11-22 15:26

    I'm on node 10 and child process 1.0.2. The data from python is a byte array and has to be converted. Just another quick example of making a http request in python.

    node

    const process = spawn("python", ["services/request.py", "https://www.google.com"])
    
    return new Promise((resolve, reject) =>{
        process.stdout.on("data", data =>{
            resolve(data.toString()); // <------------ by default converts to utf-8
        })
        process.stderr.on("data", reject)
    })
    

    request.py

    import urllib.request
    import sys
    
    def karl_morrison_is_a_pedant():   
        response = urllib.request.urlopen(sys.argv[1])
        html = response.read()
        print(html)
        sys.stdout.flush()
    
    karl_morrison_is_a_pedant()
    

    p.s. not a contrived example since node's http module doesn't load a few requests I need to make

    0 讨论(0)
提交回复
热议问题