Python3.12中debugpy报错:module 'thread'无start_new_thread属性
问题排查:Python 3.12.2 + aiohttp 异步请求引发AttributeError
问题场景
使用Python 3.12.2,通过aiohttp编写异步代码获取网站端点数据,代码如下:
from aiohttp import ClientSession as session import asyncio async def get_api_data(api_url): try: async with session.post(api_url, data={"limit": 10000, "page": 1}) as response: response.raise_for_status() data = asyncio.run(response.json()) return data except session as e: print(f"Error getting API data: {e}") return None asyncio.create_task(get_api_data("url"))
运行时触发AttributeError,错误栈指向debugpy依赖的pydevd库中线程补丁逻辑,提示:module 'thread' has no attribute 'start_new_thread'。已升级Python至3.12.2并更新相关依赖库,但问题仍未解决。
问题分析与解决方案
1. 代码本身的错误修正
先修正代码中的异步逻辑错误,这些错误可能间接触发调试库的异常:
response.json()是协程对象,不能用asyncio.run()调用,需改用await- 异常捕获逻辑错误:
except session as e无效,应捕获aiohttp.ClientError及其子类 asyncio.create_task()需要在异步上下文(如asyncio.run()包裹的主函数)中执行,否则无法运行
修正后的代码:
from aiohttp import ClientSession, ClientError import asyncio async def get_api_data(api_url): try: async with ClientSession() as session: async with session.post(api_url, data={"limit": 10000, "page": 1}) as response: response.raise_for_status() data = await response.json() return data except ClientError as e: print(f"Error getting API data: {e}") return None async def main(): await get_api_data("your_actual_api_url") if __name__ == "__main__": asyncio.run(main())
2. 解决thread模块的AttributeError问题
Python 3.12中已彻底移除thread模块(该模块在Python 3.x中早已标记为废弃,官方推荐使用threading),而旧版本的pydevd/debugpy仍在调用该模块的start_new_thread方法。解决方式:
- 升级debugpy到兼容Python 3.12的最新版本:
pip install --upgrade debugpy - 若升级debugpy后问题仍存在,直接升级pydevd:
pip install --upgrade pydevd - 若使用IDE(如VS Code)调试,确保IDE的Python插件已更新到支持Python 3.12的版本,避免旧插件携带的旧版依赖引发冲突
- 临时 workaround(不推荐长期使用):若无法立即升级依赖,可在代码开头添加兼容补丁:
import sys import threading # 为thread模块添加兼容映射 sys.modules['thread'] = threading
内容的提问来源于stack exchange,提问作者Abdulrahman Hocaoglu
相关产品推荐
相关产品推荐

