更改.so文件的Cython命名规则

发布于 2021-01-29 17:02:39

我正在使用Cython从Python模块生成一个共享对象。编译输出将写入build/lib.linux-x86_64-3.5/<Package>/<module>.cpython-35m-x86_64-linux-gnu.so。是否可以更改命名规则?我希望文件名<module>.so不带解释器版本或拱形附录。

关注者
0
被浏览
45
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    似乎setuptools没有提供完全更改或摆脱后缀的选项。魔术发生在distutils/command/build_ext.py

    def get_ext_filename(self, ext_name):
        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
    

    似乎我将需要添加构建后重命名操作。


    从08/12/2016更新:

    好的,我忘了实际发布解决方案。实际上,我通过重载内置install_lib命令来实现了重命名操作。这是逻辑:

    from distutils.command.install_lib import install_lib as _install_lib
    
    def batch_rename(src, dst, src_dir_fd=None, dst_dir_fd=None):
        '''Same as os.rename, but returns the renaming result.'''
        os.rename(src, dst,
                  src_dir_fd=src_dir_fd,
                  dst_dir_fd=dst_dir_fd)
        return dst
    
    class _CommandInstallCythonized(_install_lib):
        def __init__(self, *args, **kwargs):
            _install_lib.__init__(self, *args, **kwargs)
    
        def install(self):
            # let the distutils' install_lib do the hard work
            outfiles = _install_lib.install(self)
            # batch rename the outfiles:
            # for each file, match string between
            # second last and last dot and trim it
            matcher = re.compile('\.([^.]+)\.so$')
            return [batch_rename(file, re.sub(matcher, '.so', file))
                    for file in outfiles]
    

    现在您要做的就是在setup函数中重载命令:

    setup(
        ...
        cmdclass={
            'install_lib': _CommandInstallCythonized,
        },
        ...
    )
    

    尽管如此,我对重载标准命令还是不满意。如果您找到更好的解决方案,请将其发布,我会接受您的回答。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看