如何从Node.js调用Python函数 [英] How to call a Python function from Node.js

查看:252
本文介绍了如何从Node.js调用Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Express Node.js应用程序,但我也有一个可以在Python中使用的机器学习算法.我可以通过Node.js应用程序调用Python函数来利用机器学习库的功能吗?

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 to make use of the power of machine learning 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:

const spawn = require("child_process").spawn;
const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);

然后要做的就是确保您在Python脚本中为import sys,然后可以使用sys.argv[1]访问arg1,使用sys.argv[2]访问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.

要将数据发送回节点,只需在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:

pythonProcess.stdout.on('data', (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.

这篇关于如何从Node.js调用Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆