Package only binary compiled .so files of a python library compiled with Cython

前端 未结 4 1001
说谎
说谎 2020-12-14 03:47

I have a package named mypack which inside has a module mymod.py, and the __init__.py. For some reason that is not in debate, I need

4条回答
  •  北海茫月
    2020-12-14 04:28

    While packaging as a wheel is definitely what you want, the original question was about excluding .py source files from the package. This is addressed in Using Cython to protect a Python codebase by @Teyras, but his solution uses a hack: it removes the packages argument from the call to setup(). This prevents the build_py step from running which does, indeed, exclude the .py files but it also excludes any data files you want included in the package. (For example my package has a data file called VERSION which contains the package version number.) A better solution would be replacing the build_py setup command with a custom command which only copies the data files.

    You also need the __init__.py file as described above. So the custom build_py command should create the __init_.py file. I found that the compiled __init__.so runs when the package is imported so all that is needed is an empty __init__.py file to tell Python that the directory is a module which is ok to import.

    Your custom build_py class would look like:

    import os
    from setuptools.command.build_py import build_py
    
    class CustomBuildPyCommand(build_py):
        def run(self):
            # package data files but not .py files
            build_py.build_package_data(self)
            # create empty __init__.py in target dirs
            for pdir in self.packages:
                open(os.path.join(self.build_lib, pdir, '__init__.py'), 'a').close()
    

    And configure setup to override the original build_py command:

    setup(
       ...
       cmdclass={'build_py': CustomBuildPyCommand},
    )
    

提交回复
热议问题