将Python脚本连接到Nodejs
完成Node.js的新功能。最近,我收到一个任务,用python从web上抓取一个网站,并使用Node.js中的python shell包将python脚本连接到Node.js。我已经完成了刮削部分,但对Node.js没有任何先验知识。您能指导我如何解决这个问题吗?因为您必须使用将Python脚本连接到Nodejs,python,node.js,Python,Node.js,完成Node.js的新功能。最近,我收到一个任务,用python从web上抓取一个网站,并使用Node.js中的python shell包将python脚本连接到Node.js。我已经完成了刮削部分,但对Node.js没有任何先验知识。您能指导我如何解决这个问题吗?因为您必须使用python shell包,并且假设您的源文件是my_file.py,您只需阅读 import {PythonShell} from 'python-shell'; let pyshell = new PythonShe
python shell
包,并且假设您的源文件是my_file.py
,您只需阅读
import {PythonShell} from 'python-shell';
let pyshell = new PythonShell('my_script.py'); // 1
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message); // here there will be logged your pyoutput
}); // 2
// end the input stream and allow the process to exit
pyshell.end(function (err,code,signal) {
if (err) throw err;
console.log('The exit code was: ' + code);
console.log('The exit signal was: ' + signal);
console.log('finished');
console.log('finished');
}); // 3
此脚本的作用:
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
// 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());
} )
}
//将代码另存为start.js
保存Python脚本和服务器脚本代码后,通过以下命令从其源文件夹运行代码:
node start.js
通过以下链接访问应用程序:
localhost:3000/name?firstname=“输入名字”&lastname=“输入姓氏”
例如:localhost:3000/name?firstname=Ram&lastname=Sharma您需要对python程序的输出做什么?我想向本地服务器显示已删除的内容。或者可能有帮助。另外,如果您可以共享您尝试过的代码,那就更好了。通常您会提供示例python脚本,然后尝试为其他人编写节点脚本,以帮助您完成实现。顺便说一句,
pythonshell
在npm
上不存在,您的意思是说pythonshell
?