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

查看:39
本文介绍了如何从 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?

推荐答案

我所知道的最简单的方法是使用 node 自带的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]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()

然后节点可以使用:

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天全站免登陆