如何使用简单的安装后脚本扩展distutils?

blo*_*kie 38 python distutils

我需要在安装模块和程序后运行一个简单的脚本.我在找到如何做到这一点的直接文档方面遇到了一些麻烦.看起来我需要从distutils.command.install继承,重写一些方法并将此对象添加到安装脚本.虽然细节有点模糊,但对于这样一个简单的钩子来说似乎需要付出很多努力.有谁知道一个简单的方法来做到这一点?

小智 33

我通过distutils源挖了一天,足够了解它来制作一堆自定义命令.它不漂亮,但确实有效.

import distutils.core
from distutils.command.install import install
...
class my_install(install):
    def run(self):
        install.run(self)
        # Custom stuff here
        # distutils.command.install actually has some nice helper methods
        # and interfaces. I strongly suggest reading the docstrings.
...
distutils.core.setup(..., cmdclass=dict(install=my_install), ...)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,乔。我已经发现并发布了类似的答案。不过你来得比较早,所以享受绿色吧:) (2认同)

blo*_*kie 16

好的,我明白了.这个想法基本上是扩展其中一个distutils命令并覆盖run方法.要告诉distutils使用新类,您可以使用cmdclass变量.

from distutils.core import setup
from distutils.command.install_data import install_data

class post_install(install_data):
    def run(self):
        # Call parent 
        install_data.run(self)
        # Execute commands
        print "Running"

setup(name="example",
      cmdclass={"install_data": post_install},
      ...
      )
Run Code Online (Sandbox Code Playgroud)

希望这会帮助别人.


Wol*_*tan 7

我无法让Joe Wreschnig的回答工作并调整他的答案,类似于扩展的distutils 文档.我想出了这个在我的机器上工作正常的代码.

from distutils import core
from distutils.command.install import install
...
class my_install(install):
    def run(self):
        install.run(self)
        # Custom stuff here
        # distutils.command.install actually has some nice helper methods
        # and interfaces. I strongly suggest reading the docstrings.
...
distutils.core.setup(..., cmdclass={'install': my_install})
Run Code Online (Sandbox Code Playgroud)

注意:我没有编辑Joe的答案,因为我不确定为什么他的答案不适用于我的机器.

  • @cpburnz我修正了另一个答案,因为它最有可能是人们会先尝试的. (3认同)
  • Joe Wreschnig的回答没有用,因为`distutils.command.install`是安装模块,他打算扩展的类是`distutils.command.install.install`. (2认同)