在Node.js中使用PythonShell时写入结束错误

时间:2017-03-26 11:24:06

标签: javascript python node.js

我尝试使用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> &nbsp; &nbsp;at writeAfterEnd (_stream_writable.js:167:12)
<br> &nbsp; &nbsp;at Socket.Writable.write (_stream_writable.js:214:5)
<br> &nbsp; &nbsp;at Socket.write (net.js:634:40)
<br> &nbsp; &nbsp;at PythonShell.send (C:\Users\Chanon\Desktop\SIP\node_modules\python-shell\index.js:205:16)
<br> &nbsp; &nbsp;at Object.handle (C:\Users\Chanon\Desktop\SIP\server.js:35:10)
<br> &nbsp; &nbsp;at next_layer (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\route.js:113:13)
<br> &nbsp; &nbsp;at Route.dispatch (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\route.js:117:5)
<br> &nbsp; &nbsp;at C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:222:24
<br> &nbsp; &nbsp;at Function.proto.process_params (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:288:12)
<br> &nbsp; &nbsp;at next (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:216:19)
<br> &nbsp; &nbsp;at next (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:180:38)
<br> &nbsp; &nbsp;at Layer.handle (C:\Users\Chanon\Desktop\SIP\server.js:26:2)
<br> &nbsp; &nbsp;at trim_prefix (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:263:17)
<br> &nbsp; &nbsp;at C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:225:9
<br> &nbsp; &nbsp;at Function.proto.process_params (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:288:12)
<br> &nbsp; &nbsp;at next (C:\Users\Chanon\Desktop\SIP\node_modules\express\lib\router\index.js:216:19)

提前谢谢

1 个答案:

答案 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();
   });
});