[英]How to kill a twisted websocket server programmatically
如何以編程方式殺死 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 秒的時間。 這樣他們就有幾秒鍾的時間優雅地完成某件事。
twisted.internet.reactor.stop()
是導致反應器關閉的方式。 這通常是導致基於 Twisted 的程序退出的原因(當然,如果程序在反應器關閉后執行更多操作,則不一定必須退出 - 但這種情況並不常見)。
但是,聽起來您似乎不想知道在進程內部運行什么 Python 代碼來結束它。 您想知道其他一些進程可以對基於 Twisted 的進程執行哪些操作以使其退出。 您提供了兩種解決方案 - KeyboardInterrupt 和 SIGKILL。 您沒有提到為什么這兩種解決方案都不合適。 他們對我來說似乎很好。
如果您對 SIGKILL 感到不舒服(畢竟您不應該這樣,您的程序可能會因多種原因而過早終止,您應該准備好處理這個問題),那么您可能忽略了 KeyboardInterrupt 是僅僅是默認 SIGINT 處理程序在 Python 程序中引發的異常。
如果您將 SIGINT 發送到基於 Twisted 的進程,那么在正常使用情況下,這將停止反應器並允許有序關閉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.