Windows下Python3.12使用Cassandra驱动报DependencyException错误
Cassandra Python驱动连接报错解决(Windows+Python3.12.3)
问题场景
环境:Windows系统,Python 3.12.3,Cassandra Python驱动3.29.1
连接本地Cassandra时触发如下报错:
--------------------------------------------------------------------------- DependencyException Traceback (most recent call last) Cell In[16], line 4 1 # This should make a connection to a Cassandra instance your local machine 2 # (127.0.0.1) ----> 4 from cassandra.cluster import Cluster 5 try: 6 cluster = Cluster(['127.0.0.1']) File c:\Users\12145\AppData\Local\Programs\Python\Python312\Lib\site-packages\cassandra\cluster.py:173, in init cassandra.cluster() DependencyException: Unable to load a default connection class The following exceptions were observed: - The C extension needed to use libev was not found. This probably means that you didn't have the required build dependencies when installing the driver. See http://datastax.github.io/python-driver/installation.html#c-extensions for instructions on installing build dependencies and building the C extension. - Unable to import asyncore module. Note that this module has been removed in Python 3.12 so when using the driver with this version (or anything newer) you will need to use one of the other event loop implementations.
核心原因
- Python 3.12移除了
asyncore模块,而3.29.1版本的Cassandra驱动默认依赖该模块作为事件循环 - 安装驱动时缺少编译C扩展的依赖,导致libev相关的C扩展未成功构建
解决步骤
方案1:升级Cassandra驱动到支持Python3.12的版本
3.29.1版本发布于2023年,不兼容Python3.12。直接升级到最新版驱动即可解决asyncore依赖问题,同时新版本会自动适配Python3.12的事件循环:
# 卸载旧版本 pip uninstall -y cassandra-driver # 安装最新版 pip install cassandra-driver --upgrade
方案2:指定替代事件循环(不升级驱动时使用)
如果无法升级驱动,可在导入Cluster前手动指定兼容Python3.12的事件循环:
- 使用Selector事件循环(无需额外依赖):
import cassandra # 指定Selector事件循环 cassandra.cluster.DEFAULT_EVENT_LOOP_CLASS = 'cassandra.io.selectoreventloop.SelectorEventLoop' from cassandra.cluster import Cluster cluster = Cluster(['127.0.0.1']) session = cluster.connect() - 使用Gevent事件循环(需额外安装依赖):
pip install geventimport cassandra cassandra.cluster.DEFAULT_EVENT_LOOP_CLASS = 'cassandra.io.geventeventloop.GeventEventLoop' from cassandra.cluster import Cluster cluster = Cluster(['127.0.0.1']) session = cluster.connect()
方案3:修复C扩展问题(可选,提升性能)
如果需要启用libev的C扩展以获得更好的性能,需先安装编译依赖:
- 安装Visual Studio Build Tools,勾选MSVC v143 - VS 2022 C++ x64/x86生成工具和对应系统版本的Windows SDK
- 重新安装驱动并强制编译C扩展:
pip uninstall -y cassandra-driver pip install cassandra-driver --no-binary :all:
内容的提问来源于stack exchange,提问作者sai
相关产品推荐
相关产品推荐

