使用子进程spawn()方法从Node.js运行Python脚本
Node.js是最常用的Web开发技术之一,但它不支持机器学习、深度学习和人工智能库。幸运的是,Python支持所有这些功能以及更多其他功能。Python的Django框架可以利用Python的这种功能,并为使用机器学习和人工智能构建新型Web应用程序提供支持。
对于那些不熟悉Django框架但使用Node.js框架的开发人员来说,也可以通过Node.js的子进程模块受益于Python。
Node.js的子进程模块提供了在JavaScript之外的其他语言(如Python)中运行脚本或命令的功能。我们可以将机器学习算法、深度学习算法和Python库提供的许多功能实现到Node.js应用程序中。子进程允许我们在Node.js应用程序中运行Python脚本,并将数据流入/流出Python脚本。
child_process.spawn(): This method helps us to spawn child process asynchronously.
让我们创建一个简单的Python脚本,它将作为命令行参数接收两个参数:名字和姓氏,然后显示它们。稍后,我们将从Node JS应用程序中运行该脚本,并在浏览器窗口中显示输出。
Python脚本:
import sys
# Takes first name and last name via command
# line arguments and then display them
print("Output from Python")
print("First name: " + sys.argv[1])
print("Last name: " + sys.argv[2])
# save the script as hello.py
Node JS 服务器代码:
// import express JS module into app
// and creates its variable.
var express = require('express');
var app = express();
// Creates a server which runs on port 3000 and
// can be accessed through localhost:3000
app.listen(3000, function() {
console.log('server running on port 3000');
} )
// Function callName() is executed whenever
// url is of the form localhost:3000/name
app.get('/name', callName);
function callName(req, res) {
// Use child_process.spawn method from
// child_process module and assign it
// to variable spawn
var spawn = require("child_process").spawn;
// Parameters passed in spawn -
// 1. type_of_script
// 2. list containing Path of the script
// and arguments for the script
// E.g : http://localhost:3000/name?firstname=Mike&lastname=Will
// so, first name = Mike and last name = Will
var process = spawn('python',["./hello.py",
req.query.firstname,
req.query.lastname] );
// Takes stdout data from script which executed
// with arguments and send this data to res object
process.stdout.on('data', function(data) {
res.send(data.toString());
} )
}
// save code as start.js
保存Python脚本和服务器脚本代码之后,通过以下命令从源文件夹中运行代码:
node start.js
通过链接访问应用程序:
localhost:3000/name?firstname="Enter first name"&lastname="Enter last name"
For e g. : localhost:3000/name?firstname=Ram&lastname=Sharma
输出:

应用:
- 此方法可作为REST API的替代方法使用。
- 此方法可以帮助我们的Web应用程序利用其他语言特殊功能,而这些功能目前在JavaScript中还不可用。
- 可以在Python中实现机器学习模块,然后使用此方法在Web应用程序中利用它们。
参考资料:
- https://nodejs.org/api/child_process.html
极客教程