如何在setup.py中执行自定义生成步骤?

时间:2013-01-21 15:31:27

标签: python setuptools distutils

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

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

2 个答案:

答案 0 :(得分:12)

我花了很多时间搞清楚这一点,各种各样的建议都以各种方式打破了 - 它们打破了依赖关系的安装,或者他们没有在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

然后,在调用setup函数时,传递arg:

cmdclass={'install': install_}

您可以使用相同的构思而不是安装,自己编写装饰器以使其更容易等。这已通过pip测试,并直接'python setup.py install'调用。

答案 1 :(得分:2)

最好的方法是编写自定义的build_coffeescript命令并使其成为构建的子命令。在对类似/重复问题的其他回复中给出了更多细节,例如这一个:

https://stackoverflow.com/a/1321345/150999

相关问题