从节点运行Python脚本。js使用子进程spawn()方法

节点。js是最常用的web开发技术之一,但它缺乏对机器学习、深度学习和人工智能库的支持。幸运的是,Python支持所有这些以及更多其他特性。Django Framework for Python可以利用Python的这一功能,并为使用机器学习和人工智能构建新时代的web应用程序提供支持。

null

对于那些不熟悉Django框架但使用Node JS框架的开发人员,也可以从中受益 Python为节点JS使用子进程模块 .

Node JS的子进程模块也提供了用JavaScript以外的语言(比如Python)运行脚本或命令的功能。我们可以在Node JS应用程序中实现机器学习算法、深度学习算法和Python库提供的许多功能。子进程允许我们在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


节点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
// 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

输出:

图片[1]-从节点运行Python脚本。js使用子进程spawn()方法-yiteyi-C++库

应用:

  1. 这种方法可以替代REST API使用。
  2. 这种方法可以帮助我们的web应用程序从其他语言的特殊功能中获益,这些功能目前在javascript中不可用
  3. 机器学习模块可以用Python实现,然后用这种方法在web应用程序中使用它们。

参考:

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享