I have an Express NodeJS application, but I also have a MachineLearning algorithm to use in Python. Is there any way I can call Python functions from my NodeJS application to make use of the power of MachineLearning libraries?
解决方案
Easiest way I know of is to use "child_process" package which comes packaged with node.
Then you can do something like:
var spawn = require("child_process").spawn;
var process = spawn('python',["path/to/script.py", arg1, arg2, ...]);
Then all you have to do is make sure that you import sys in your python script, and then you can access arg1 using sys.argv[1], arg2 using sys.argv[2], and so on.
To send data back to node just do the following in the python script:
print(dataToSendBack)
sys.stdout.flush()
And then node can listen for data using:
process.stdout.on('data', function (data){
// Do something with the data returned from python script
});
Since this allows multiple arguments to be passed to a script using spawn, you can restructure a python script so that one of the arguments decides which function to call, and the other argument gets passed to that function, etc.
Hope this was clear. Let me know if something needs clarification.