From 6029b5482ed8c7384b7b96c5a9f90b0f2f1bcf7b Mon Sep 17 00:00:00 2001 From: kalicyh <34980061+kalicyh@users.noreply.github.com> Date: Fri, 7 Mar 2025 11:36:05 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=88=20perf:=20=E4=BC=98=E9=9B=85?= =?UTF-8?q?=E7=9A=84=E9=80=80=E5=87=BA=E8=BF=9B=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main/xiaozhi-server/app.py | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/main/xiaozhi-server/app.py b/main/xiaozhi-server/app.py index bd23c7bcd..80e48443d 100644 --- a/main/xiaozhi-server/app.py +++ b/main/xiaozhi-server/app.py @@ -1,10 +1,15 @@ import asyncio +import sys from config.settings import load_config, check_config_file from core.websocket_server import WebSocketServer from core.utils.util import check_ffmpeg_installed TAG = __name__ +async def wait_for_exit(): + """在 Windows 上等待用户按 Ctrl + C""" + loop = asyncio.get_running_loop() + await loop.run_in_executor(None, sys.stdin.read) # 监听标准输入(阻塞) async def main(): check_config_file() @@ -16,11 +21,19 @@ async def main(): ws_task = asyncio.create_task(ws_server.start()) try: - # 等待 WebSocket 服务器运行 - await ws_task + await wait_for_exit() # Windows 下用 sys.stdin.read() 监听退出 + except asyncio.CancelledError: + print("任务被取消,清理资源中...") finally: ws_task.cancel() - + try: + await ws_task # 确保 WebSocket 任务正确关闭 + except asyncio.CancelledError: + pass # 忽略取消异常 + print("服务器已关闭,程序退出。") if __name__ == "__main__": - asyncio.run(main()) + try: + asyncio.run(main()) + except KeyboardInterrupt: + print("手动中断,程序终止。")