我尝试使用PythonShell模块从我的Node.js api运行python脚本。它第一次完美运行。但是当我再次调用api时,会发生Write after end错误。这是我的代码的一部分。
导入部分。
var PythonShell = require('python-shell');
var pyshell = new PythonShell('script.py');
调用python脚本的路由器部分。
router.get('/sendinfo', function(req, res,next) {
pyshell.send(JSON.stringify([1,2,3,4,6]));
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err){
throw err;
};
console.log('finished');
res.json({ message: 'api finished' });
next();
});
});
这是一个全文错误
Error: write after end
<br> at writeAfterEnd (_stream_writable.js:167:12)
<br> at Socket.Writable.write (_stream_writable.js:214:5)
<br> at Socket.write (net.js:634:40)
<br> at PythonShell.send (C:\Users\Chanon\Desktop\SIP\node_modules\python-shell\index.js:205:16)
<br> at Object.handle (C:\Users\Chanon\Desktop\SIP\server.js:35:10)
<br> at next_layer (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\route.js:113:13)
<br> at Route.dispatch (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\route.js:117:5)
<br> at C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:222:24
<br> at Function.proto.process_params (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:288:12)
<br> at next (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:216:19)
<br> at next (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:180:38)
<br> at Layer.handle (C:\Users\Chanon\Desktop\SIP\server.js:26:2)
<br> at trim_prefix (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:263:17)
<br> at C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:225:9
<br> at Function.proto.process_params (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:288:12)
<br> at next (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:216:19)
提前谢谢
答案 0 :(得分:0)
我通过
找到了解决方案var pyshell = new PythonShell('script.py');
像这样的api
router.get('/sendinfo', function(req, res,next) {
var pyshell = new PythonShell('script.py');
pyshell.send(JSON.stringify([1,2,3,4,6]));
pyshell.on('message', function (message) {
console.log(message);
});
pyshell.end(function (err) {
if (err){
throw err;
};
console.log('finished');
res.json({ message: 'api finished' });
next();
});
});