How to call a Python function from Node.js

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

提交回复
热议问题