0
我试图在nodejs内执行几个python脚本。代码如下所示。我想要做的是在for循环内逐个执行不同的python脚本。并在一个脚本结束后立即将json响应发送给客户端。使用python-shell发送多个来自nodejs的响应
var PythonShell = require('python-shell');
var express = require('express'), app = express();
app.get('/', function (req, res) {
res.setHeader('Content-Type', 'text/html');
pl_list=["test", "test2"]
for (var i=0; i<= pl_list.length-1; i++) {
output="";
var pyshell = new PythonShell('./'+pl_list[i]+'.py')
pyshell.on('message', function (message)
{console.log(message);output+=message;});
pyshell.end(function (err) {
if (err){
console.log('error occured ---- '+err);
}
else{
console.log('update finished');
res.write(JSON.stringify({"finsihed":true, "product_line":pl_list[i]}));
}
});
}
//res.end()
});
app.listen(5000, function() {
console.log('The web server is running. Please open http://localhost:5000/ in your browser.');
});
不幸的是我得到了响应,{"finsihed":true}
实际输出必须 {"finsihed":true, "product_line":"test"}{"finsihed":true, "product_line":"test2"}
有谁能够告诉我,我在做什么错在这里。提前致谢!
感谢您的帮助,但是当我执行上面的代码的响应'{ “finsihed”:真实的,“product_line “:”test2“} {”finsihed“:true,”product_line“:”test“}'而不是'{”finsihed“:true,”product_line“:”test“} {”finsihed“:true,”product_line“ :“test2”}' –
响应必须与'pl_list'中的值相同。 –
如果您希望您的响应始终处于相同顺序,则必须使用s ome工具可以很好地处理异步操作。我编辑我的代码并选择使用承诺。告诉我它是否适合你。 –