我有一个Express Node.js应用程序,但我也有一个机器学习算法在Python中使用。是否有一种方法可以从我的Node.js应用程序调用Python函数来利用机器学习库的强大功能?
当前回答
我知道的最简单的方法是使用“child_process”包,它随node一起打包。
然后你可以这样做:
const spawn = require("child_process").spawn;
const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);
然后你要做的就是确保你在python脚本中导入了sys,然后你就可以使用sys访问arg1了。Argv [1], arg2使用sys。Argv[2],等等。
要将数据发送回节点,只需在python脚本中执行以下操作:
print(dataToSendBack)
sys.stdout.flush()
然后node可以使用以下命令监听数据:
pythonProcess.stdout.on('data', (data) => {
// Do something with the data returned from python script
});
由于这允许使用spawn将多个参数传递给脚本,您可以重新构造python脚本,以便其中一个参数决定调用哪个函数,而另一个参数传递给该函数,等等。
希望这是清楚的。如果有需要澄清的地方请告诉我。
其他回答
通过extrabacon, Python -shell模块是一种从Node.js运行Python脚本的简单方法,具有基本但有效的进程间通信和更好的错误处理。
安装:
npm: NPM安装python-shell。
或者用纱线: 纱线加蟒壳
运行一个简单的Python脚本:
const PythonShell = require('python-shell').PythonShell;
PythonShell.run('my_script.py', null, function (err) {
if (err) throw err;
console.log('finished');
});
运行带有参数和选项的Python脚本:
const PythonShell = require('python-shell').PythonShell;
var options = {
mode: 'text',
pythonPath: 'path/to/python',
pythonOptions: ['-u'],
scriptPath: 'path/to/my/scripts',
args: ['value1', 'value2', 'value3']
};
PythonShell.run('my_script.py', options, function (err, results) {
if (err)
throw err;
// Results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
要获得完整的文档和源代码,请访问https://github.com/extrabacon/python-shell
const util = require('util');
const exec = util.promisify(require('child_process').exec);
function runPythonFile() {
const { stdout, stderr } = await exec('py ./path_to_python_file -s asdf -d pqrs');
if (stdout) { // do something }
if (stderr) { // do something }
}
欲了解更多信息,请访问Nodejs官方子进程页面:https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback
你可以把你的python编译,然后像调用javascript一样调用它。我已经成功地为screeps做了这件事,甚至让它在浏览器中运行la brython。
您现在可以使用支持Python和Javascript的RPC库,例如zerorpc
从他们的头版:
node . js的客户
var zerorpc = require("zerorpc");
var client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
client.invoke("hello", "RPC", function(error, res, more) {
console.log(res);
});
Python服务器
import zerorpc
class HelloRPC(object):
def hello(self, name):
return "Hello, %s" % name
s = zerorpc.Server(HelloRPC())
s.bind("tcp://0.0.0.0:4242")
s.run()
我在节点10和子进程1.0.2上。来自python的数据是一个字节数组,必须进行转换。这是另一个用python发出http请求的快速示例。
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.不是一个人为的例子,因为节点的http模块不加载我需要做的一些请求
推荐文章
- Matplotlib错误-没有名为tkinter的模块
- 0到1之间的随机数?
- 使用Boto3将S3对象作为字符串打开
- "pip install——editable ./" vs "python setup.py develop"
- Pandas:索引数据帧时的多个条件-意外行为
- 如何更改Django应用程序的名称?
- 如何在python抽象类中创建抽象属性?
- Haskell对Node.js的响应是什么?
- “克隆”行或列向量
- 在python shell中按方向键时看到转义字符
- 在pip install中方括号是什么意思?
- 使用Matplotlib以非阻塞的方式绘图
- 使用sklearn缩放Pandas数据框架列
- npm不工作-“读取ECONNRESET”
- npm install from Git在特定的版本