我该如何阻止PythonShell

时间:2016-05-10 21:34:14

标签: python node.js

如何在Node.js中杀死/停止PythonShell执行的Python脚本的执行?

我在交互模式下运行,输出通过socket.io发送到给定的房间。如果没有更多的客户端连接到这个房间我想停止python脚本执行。这是我的代码片段。 感谢。

app.get('/live', function(req, res) {
var room = req.query.room;

var shell = new pythonShell('test_live.py');

shell.on('message', function(message) {
    var clientNumber = 0;
    if ( room in io.sockets.adapter.rooms){
      clientNumber = io.sockets.adapter.rooms[room].length;
    }
    console.log(clientNumber);
    if (clientNumber> 0){
      // handle message (a line of text from stdout)
      io.to(room).emit('send:logentry', {
          logentry: room + " " + message
      });
    }else{
      // I want to kill the python script execution
    }

    console.log("Send to" + room + ": " + message);
});

// end the input stream and allow the process to exit
shell.end(function(err) {
    if (err) throw err;
    res.sendStatus(200);
});

});

1 个答案:

答案 0 :(得分:4)

因此,根据文档herePythonShell实例具有由childProcess创建的child_process.spawn属性,然后基于此answer,您应该能够通过

杀死它
shell.childProcess.kill('SIGINT');