【发布时间】:2020-12-12 17:42:12
【问题描述】:
如何以编程方式终止 websocket 服务器?我将把这台服务器与其他东西一起部署到生产环境中。我喜欢构建一个单独的 python 脚本,向所有东西发送终止信号。如果没有用户键盘中断或 kill -9,我无法弄清楚如何杀死这个东西。
sys.exit() 不起作用。
psutil 和 terminate() 也不起作用
import os
import psutil
current_system_pid = os.getpid()
ThisSystem = psutil.Process(current_system_pid)
ThisSystem.terminate()
我没有想法。现在我在命令行中用 kill -9 杀死它。
当我以各种方式杀死它时,它往往会在下面看到这条消息,但脚本仍在运行
2020-12-12 12:24:54-0500 [autobahn.twisted.websocket.WebSocketServerFactory] (TCP Port 8080 Closed)
2020-12-12 12:24:54-0500 [-] Stopping factory <autobahn.twisted.websocket.WebSocketServerFactory object at 0x110680f28>
高速公路安装:
pip install autobahn[twisted]
代码:
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
import sys
from twisted.python import log
from twisted.internet import reactor
class MyServerProtocol(WebSocketServerProtocol):
def onConnect(self, request):
print("Client connecting: {0}".format(request.peer))
def onOpen(self):
print("WebSocket connection open.")
def onMessage(self, payload, isBinary):
print("Text message received: {0}".format(payload.decode('utf8')))
# echo back message verbatim
# self.sendMessage(payload, isBinary)
def onClose(self, wasClean, code, reason):
print("WebSocket connection closed: {0}".format(reason))
def StopWebsocketServer():
PrintAndLog_FuncNameHeader("Begin")
reactor.stop()
PrintAndLog_FuncNameHeader("End")
if __name__ == '__main__':
# TODO remove the logging that came in the example
log.startLogging(sys.stdout)
factory = WebSocketServerFactory("ws://127.0.0.1:8080")
factory.protocol = MyServerProtocol
# note to self: if using putChild, the child must be bytes...
reactor.listenTCP(Port_ws, factory)
reactor.run()
解决方案使用@Jean-Paul Calderone 的回答:
import os
import signal
os.kill(os.getpid(), signal.SIGKILL)
我有一个外部 python 脚本,它向我的每个 python 脚本发送一个终止信号。终止信号只是每个脚本都知道要查找的文件的存在。一旦该终止信号出现,每个脚本都知道它在被终止之前还有 x 秒的时间。这样他们就有几秒钟的时间优雅地完成某件事。
【问题讨论】:
-
你考虑过
os.kill()吗? -
os.kill 确实适用于 signal.SIGKILL。谢谢
标签: python python-3.x macos twisted autobahn