python - 如何在 setup.py 中执行自定义构建步骤?

标签 python setuptools distutils

distutils 模块允许将资源文件与 Python 模块一起包含和安装。如果在构建过程中应该生成资源文件,如何正确地包含它们?

例如,该项目是一个 Web 应用程序,其中包含 CoffeeScript 源代码,应将其编译为 JavaScript 并包含在 Python 包中。有没有办法将其集成到正常的 sdist/bdist 进程中?

最佳答案

我花了很长时间才弄清楚这个问题,那里的各种建议以各种方式被破坏了——它们破坏了依赖项的安装,或者它们在 pip 中不起作用,等等。这是我的解决方案:

在 setup.py 中:

from setuptools import setup, find_packages
from setuptools.command.install import install
from distutils.command.install import install as _install

class install_(install):
    # inject your own code into this func as you see fit
    def run(self):
        ret = None
        if self.old_and_unmanageable or self.single_version_externally_managed:
            ret = _install.run(self)
        else:
            caller = sys._getframe(2)
            caller_module = caller.f_globals.get('__name__','')
            caller_name = caller.f_code.co_name

            if caller_module != 'distutils.dist' or caller_name!='run_commands':
                _install.run(self)
            else:
                self.do_egg_install()

        # This is just an example, a post-install hook
        # It's a nice way to get at your installed module though
        import site
        site.addsitedir(self.install_lib)
        sys.path.insert(0, self.install_lib)
        from mymodule import install_hooks
        install_hooks.post_install()
        return ret

然后,在您对设置函数的调用中,传递 arg:

cmdclass={'install': install_}

您可以使用相同的想法来构建而不是安装,为自己编写一个装饰器以使其更容易等。这已经通过 pip 和直接“python setup.py install”调用进行了测试。

关于python - 如何在 setup.py 中执行自定义构建步骤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14441955/

相关文章:

python - 高效的项目装箱算法(itertools/numpy)

python - 推送到 nexus,我得到 "Repository path must have another '/' after initial '/'"

python - 按日期对 Python 对象列表进行排序

python - 为 C++(指针)创建 swig 包装器到 python

python - 将 "scripts"作为 Python 包的一部分安装在 setup.py 中,位于用户路径上并被识别为 Python 脚本

python - 如何定义一个给定测试子目录中的所有测试使用的 pytest 固定装置?

Python:如果安装了同一个包的多个 egg 版本,我该如何具体导入我需要的版本?

python - pip 没有正确解决子/孙依赖关系

python - pip 是否处理来自 setuptools/distribute 来源的 extras_requires?

python - 使用 python 包分发运行脚本的正确方法?