FastAPI服务按Ctrl+C无法正常退出,求助解决方法
FastAPI服务无法通过Ctrl+C终止
按下Ctrl+C后进程挂起,无法返回终端。以下是相关配置、运行脚本及日志:
pyproject.toml配置
[tool.pyright] exclude = ["app/worker"] ignore = ["app/worker"] [tool.poetry] name = "api" version = "0.1.0" description = "" authors = ["SamiAlsubhi <sami@alsubhi.me>"] [tool.poetry.dependencies] python = ">=3.8,<3.9" fastapi = "^0.65.2" tortoise-orm = "^0.17.4" asyncpg = "^0.23.0" aerich = "^0.5.3" networkx = "^2.5.1" numpy = "^1.21.0" ldap3 = "^2.9.1" fastapi-jwt-auth = "^0.5.0" python-multipart = "^0.0.5" torch = "1.7.1" pyts = "0.11.0" Pint = "^0.17" Cython = "^0.29.24" python-dotenv = "^0.19.0" arq = "^0.22" uvicorn = {extras = ["standard"], version = "^0.15.0"} [tool.poetry.dev-dependencies] pytest = "^6.2.4" requests = "^2.25.1" asynctest = "^0.13.0" coverage = "^5.5" pytest-html = "^3.1.1" pytest-sugar = "^0.9.4" pytest-json-report = "^1.4.0" pytest-cov = "^2.12.1" pylint = "^2.11.1" autopep8 = "^1.5.7" black = "^22.3.0" aiosqlite = "^0.17.0" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api"
运行脚本run.py
"""本地开发环境运行API""" import os import uvicorn from dotenv import load_dotenv # 加载环境变量 load_dotenv("../.env") if __name__ == "__main__": port = os.getenv("FASTAPI_PORT") port = int(port) if port else None uvicorn.run("app.main:app", host=os.getenv("FASTAPI_HOST"), port=port, reload=True)
运行及退出日志
(trendr) sami@Samis-MBP backend % python run.py INFO: 即将监听以下目录的变化: ['/Users/name/Desktop/etc'] INFO: Uvicorn运行在 http://0.0.0.0:1000 (按CTRL+C退出) INFO: 使用watchgod启动重载进程 [70087] INFO: 启动服务器进程 [70089] INFO: 等待应用启动。 INFO: 应用启动完成。 ^CINFO: 正在关闭 INFO: 服务器进程 [70089] 已结束 INFO: ASGI 'lifespan' 协议似乎不被支持。
解决方案
禁用自动重载
启动命令中移除reload=True,改为:uvicorn.run("app.main:app", host=os.getenv("FASTAPI_HOST"), port=port)自动重载模式下,watchgod可能导致父进程无法正确捕获终止信号,禁用后通常可正常退出。
手动终止进程
若禁用重载仍无效,可通过进程ID强制终止:- 执行
ps aux | grep python查找父进程ID(即日志中的[70087]) - 执行
kill -9 <进程ID>强制终止
- 执行
检查应用资源清理逻辑
确认app.main中是否存在未正确关闭的异步资源(如数据库连接、后台任务),这些资源会阻塞进程退出。可通过FastAPI的shutdown事件显式清理:from fastapi import FastAPI app = FastAPI() @app.on_event("shutdown") async def shutdown_resources(): # 此处添加资源关闭代码,例如数据库连接关闭 await your_db_close_method()升级uvicorn版本
当前使用的uvicorn 0.15.0存在信号处理的已知问题,升级到0.20+版本可修复此类问题:poetry add uvicorn@latest --extras standard
内容的提问来源于stack exchange,提问作者Sami Al-Subhi
相关产品推荐
相关产品推荐

