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

eig*_*ein 14 python distutils setuptools

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

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

小智 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
Run Code Online (Sandbox Code Playgroud)

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

cmdclass={'install': install_}
Run Code Online (Sandbox Code Playgroud)

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


Éri*_*ujo 2

最好的方法是编写一个自定义的 build_coffeescript 命令并将其作为 build 的子命令。更多详细信息在对类似/重复问题的其他答复中给出,例如:

/sf/answers/92494181/

  • http://stackoverflow.com/q/11331175/150999 http://stackoverflow.com/a/1321345/150999 (3认同)