You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cython编译生成.pyd模块后导入提示‘找不到模块’问题求助

问题描述

我有一个位于d:/exe_project/all_files/python_files/路径下的Cython文件main_file_001.pyx,尝试编译为Python扩展模块后导入失败。

编译用的setup.py代码:

try:
    from setuptools import setup
    from setuptools import Extension
except ImportError:
    from distutils.core import setup
    from distutils.extension import Extension

from Cython.Distutils import build_ext

pat = "d:/exe_project/all_files/python_files/main_file_001.pyx"
ext_modules = [Extension("my_code_cython", [pat])]

setup(
    name='Generic model class',
    cmdclass={'build_ext': build_ext},
    ext_modules=ext_modules
)

执行python setup.py build_ext --inplace后,同目录生成了my_code_cython.cp37-win_amd64.pyd,但在另一个Python程序中执行import my_code_cython时提示“找不到模块”。

环境信息:

  • PyCharm社区版、Windows 10系统
  • Cython版本3.0.0a11
  • 编译与导入均使用Python 3.7
  • 已将.pyd所在目录添加至PYTHONPATH,sys.path输出包含D:\\exe_project\\all_files\\python_files
  • main_file_001.pyx代码:
def say_hello_to():
    print("Hello ")
排查与解决方案

1. 严格确认Python解释器一致性

即使标注了都是Python3.7,也要检查:

  • 编译时用的python命令路径,和PyCharm运行配置里的解释器路径是否完全一致(比如是否混用了全局Python和虚拟环境)
  • 分别在编译终端和PyCharm终端执行python -V,确保版本、32/64位完全匹配(Windows下位数不匹配会直接导致模块无法识别)

2. 验证.pyd文件的实际位置

build_ext --inplace偶尔会因权限或路径问题,把.pyd文件生成到build子目录里,手动确认my_code_cython.cp37-win_amd64.pyd确实在D:\\exe_project\\all_files\\python_files目录下,若不在则复制过去。

3. 手动显式添加路径

即使已经配置了PYTHONPATH,也可以在导入前手动添加路径排除环境变量加载问题:

import sys
sys.path.append("D:/exe_project/all_files/python_files")
import my_code_cython
my_code_cython.say_hello_to()

4. 降级Cython到稳定版

你使用的是Cython 3.0.0a11预览版,存在兼容性bug的概率较高,建议降级到适配Python3.7的稳定版:

pip uninstall cython
pip install cython==0.29.36

重新编译模块后再尝试导入。

5. 检查文件名大小写匹配

Windows系统默认不区分大小写,但PyCharm或Python缓存可能敏感,确保导入的模块名my_code_cython和.pyd文件名前缀完全一致(大小写、下划线都不能错)。

6. 清理PyCharm缓存

PyCharm缓存旧模块信息会导致无法识别新生成的.pyd文件:
点击File -> Invalidate Caches...,选择Invalidate and Restart,重启后再测试导入。


内容的提问来源于stack exchange,提问作者Bala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 01:21:04