Change Cython's naming rules for .so files

前端 未结 3 850
盖世英雄少女心
盖世英雄少女心 2020-12-16 18:39

I\'m using Cython to generate a shared object out of Python module. The compilation output is written to build/lib.linux-x86_64-3.5//.cpyt

3条回答
  •  眼角桃花
    2020-12-16 18:41

    This behavior has been defined in distutils package. distutils uses sysconfig and "EXT_SUFFIX" config variable:

    # Lib\distutils\command\build_ext.py
    
    def get_ext_filename(self, ext_name):
        r"""Convert the name of an extension (eg. "foo.bar") into the name
        of the file from which it will be loaded (eg. "foo/bar.so", or
        "foo\bar.pyd").
        """
        from distutils.sysconfig import get_config_var
        ext_path = ext_name.split('.')
        ext_suffix = get_config_var('EXT_SUFFIX')
        return os.path.join(*ext_path) + ext_suffix
    

    Starting with Python 3.5 "EXT_SUFFIX" variable contains platform information, for example ".cp35-win_amd64".

    I have written the following function:

    def get_ext_filename_without_platform_suffix(filename):
        name, ext = os.path.splitext(filename)
        ext_suffix = sysconfig.get_config_var('EXT_SUFFIX')
    
        if ext_suffix == ext:
            return filename
    
        ext_suffix = ext_suffix.replace(ext, '')
        idx = name.find(ext_suffix)
    
        if idx == -1:
            return filename
        else:
            return name[:idx] + ext
    

    And custom build_ext command:

    from Cython.Distutils import build_ext
    
    class BuildExtWithoutPlatformSuffix(build_ext):
        def get_ext_filename(self, ext_name):
            filename = super().get_ext_filename(ext_name)
            return get_ext_filename_without_platform_suffix(filename)
    

    Usage:

    setup(
        ...
        cmdclass={'build_ext': BuildExtWithoutPlatformSuffix},
        ...
    )
    

提交回复
热议问题