如何终止/停止由 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);
});
});
最佳答案
所以根据文档 here PythonShell
实例有一个 childProcess
属性,它是由 child_process.spawn
创建的,然后基于这个 answer你应该可以通过这样做来杀死它
shell.childProcess.kill('SIGINT');
关于python - 我怎样才能停止PythonShell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37149362/