如何从NodeJS调用Python函数 [英] How to call Python function from NodeJS
问题描述
我有一个Express NodeJS应用程序,但是我也有一个用于Python的MachineLearning算法。有什么办法可以从我的NodeJS应用程序调用Python函数来利用MachineLearning库的力量吗?
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?
推荐答案
最简单的方法我知道是使用与节点一起打包的child_process包。
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, ...]);
然后你要做的只是确保你 import sys <您的python脚本中的code>,然后您可以使用
sys.argv [1]
访问 arg1
arg2
使用 sys.argv [2]
等。
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.
要将数据发送回节点,请在python脚本中执行以下操作:
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
});
由于这允许使用spawn将多个参数传递给脚本,因此可以重构python脚本其中一个参数决定要调用哪个函数,另一个参数被传递给该函数等。
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.
这篇关于如何从NodeJS调用Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!