mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
🎈 perf: 优雅的退出 兼容mac和linux
This commit is contained in:
parent
6029b5482e
commit
34430f36f7
1 changed files with 17 additions and 5 deletions
|
|
@ -1,5 +1,6 @@
|
||||||
import asyncio
|
import asyncio
|
||||||
import sys
|
import sys
|
||||||
|
import signal
|
||||||
from config.settings import load_config, check_config_file
|
from config.settings import load_config, check_config_file
|
||||||
from core.websocket_server import WebSocketServer
|
from core.websocket_server import WebSocketServer
|
||||||
from core.utils.util import check_ffmpeg_installed
|
from core.utils.util import check_ffmpeg_installed
|
||||||
|
|
@ -7,9 +8,20 @@ from core.utils.util import check_ffmpeg_installed
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
|
||||||
async def wait_for_exit():
|
async def wait_for_exit():
|
||||||
"""在 Windows 上等待用户按 Ctrl + C"""
|
"""Windows 和 Linux 兼容的退出监听"""
|
||||||
loop = asyncio.get_running_loop()
|
loop = asyncio.get_running_loop()
|
||||||
await loop.run_in_executor(None, sys.stdin.read) # 监听标准输入(阻塞)
|
stop_event = asyncio.Event()
|
||||||
|
|
||||||
|
if sys.platform == "win32":
|
||||||
|
# Windows: 用 sys.stdin.read() 监听 Ctrl + C
|
||||||
|
await loop.run_in_executor(None, sys.stdin.read)
|
||||||
|
else:
|
||||||
|
# Linux/macOS: 用 signal 监听 Ctrl + C
|
||||||
|
def stop():
|
||||||
|
stop_event.set()
|
||||||
|
loop.add_signal_handler(signal.SIGINT, stop)
|
||||||
|
loop.add_signal_handler(signal.SIGTERM, stop) # 支持 kill 进程
|
||||||
|
await stop_event.wait()
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
check_config_file()
|
check_config_file()
|
||||||
|
|
@ -21,15 +33,15 @@ async def main():
|
||||||
ws_task = asyncio.create_task(ws_server.start())
|
ws_task = asyncio.create_task(ws_server.start())
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await wait_for_exit() # Windows 下用 sys.stdin.read() 监听退出
|
await wait_for_exit() # 监听退出信号
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
print("任务被取消,清理资源中...")
|
print("任务被取消,清理资源中...")
|
||||||
finally:
|
finally:
|
||||||
ws_task.cancel()
|
ws_task.cancel()
|
||||||
try:
|
try:
|
||||||
await ws_task # 确保 WebSocket 任务正确关闭
|
await ws_task
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
pass # 忽略取消异常
|
pass
|
||||||
print("服务器已关闭,程序退出。")
|
print("服务器已关闭,程序退出。")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue