1

How can I kill/stop the execution of a Python script executed by PythonShell in Node.js?

I run in the interactive mode and the output is emitted via socket.io into a given room. If there is no more clients attached to this room I want to stop the python script execution. Here is a snippet of my code. Thanks.

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);
});

});

Piyush Patil
  • 14,512
  • 6
  • 35
  • 54
Vincenzo
  • 85
  • 12

1 Answers1

4

So according to the doc here the PythonShell instance has a childProcess attribute which was created by child_process.spawn, and then based on this answer you should be able to kill it by doing

shell.childProcess.kill('SIGINT');
Community
  • 1
  • 1
danf1024
  • 421
  • 3
  • 3