Cythonize函数生成扩展含根目录致Wheel结构异常求助
Looks like the issue comes from misaligned path configurations between setuptools and cythonize—by default, Cython preserves the relative directory structure of your .pyx files, and without telling setuptools where your actual package lives, it ends up packing the entire _src directory into the wheel. Here's how to fix it:
1. Update Your setup.py with Correct Path Mappings
You need to explicitly tell setuptools that your package lives under the _src directory, and adjust the Cython configuration to generate extensions under the right package namespace. Here's a revised setup script:
from setuptools import setup, find_packages from Cython.Build import cythonize setup( name="your-package-name", version="0.1.0", # Map the root package namespace to our _src directory package_dir={"": "_src"}, # Auto-discover all packages inside _src (avoids manual listing) packages=find_packages(where="_src"), # Cythonize the .pyx files with proper path handling ext_modules=cythonize( # Target the .pyx files directly in _src/mylib "_src/mylib/**/*.pyx", # Ensure compatibility with Python 3 compiler_directives={"language_level": "3"}, # Optional: Force recompile if you make changes to .pyx files force=True ), # Make sure regular .py files in mylib are included too package_data={ "mylib": ["*.py"], }, )
2. Key Configuration Breakdown
package_dir={"": "_src"}: This tells setuptools that all your packages are rooted in the_srcdirectory. So when it looks for themylibpackage, it knows to check_src/mylibinstead of the project root.find_packages(where="_src"): Scans_srcfor all valid Python packages (directories with__init__.py) and includes them in the build—no need to list each package manually.cythonize("_src/mylib/**/*.pyx"): By targeting the.pyxfiles directly in their source location, and pairing this withpackage_dir, Cython will generate extension modules that belong to themylibnamespace, not the_src.mylibnamespace.package_data: Ensures that any regular.pyfiles inmylibare included in the wheel, so you don't lose non-Cythonized code.
3. Verify the Fixed Wheel Structure
Run your build command again:
python setup.py build_ext bdist_wheel clean --all
To check the structure, unpack the generated wheel using:
wheel unpack your-package-name-0.1.0-py3-none-any.whl
You should now see the correct, flat structure:
your-package-name-0.1.0/ └── mylib/ ├── __init__.py ├── module.cpython-xxxx.so # Compiled Cython module (extension varies by OS) └── [other .py files]
4. Extra Tips
- Double-check that
_src/mylib/__init__.pyis properly configured (e.g., exporting modules you want users to access). - If your Cython modules depend on external C libraries, you may need to add
include_dirsto theext_modulessetup, but that's unrelated to the directory structure issue. - Using a recent version of
setuptools(>=61.0.0) helps with more reliable package path handling.
内容的提问来源于stack exchange,提问作者SuperGeo

