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

模块和程序安装后,我需要运行一个简单的脚本。 我在查找关于如何做到这一点的简单文档方面遇到了一些麻烦。 它看起来像我需要从distutils.command.installinheritance,重写一些方法,并将此对象添加到安装脚本。 细节虽然有点朦胧,对于这样一个简单的钩子来说,这似乎是一个很大的努力。 有谁知道一个简单的方法来做到这一点?

我通过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), ...) 

好的,我明白了。 这个想法基本上是扩展一个distutils命令并覆盖run方法。 要告诉distutils使用新类,可以使用cmdclassvariables。

 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}, ... ) 

希望这会帮助别人。

我无法让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}) 

注意:我没有编辑乔的答案,因为我不确定为什么他的答案在我的机器上不起作用。

当我在这里尝试接受的答案时,我得到了一个错误(可能是因为我在这种情况下使用Python 2.6,不知道)。 对于'setup.py install'和'pip install'都发生了这种情况:

 sudo python setup.py install 

失败, 错误:setup.cfg中的错误:命令'my_install'没有这样的选项'single_version_externally_managed'

 sudo pip install . -U 

失败更详细,但也与错误:选项 – 单一版本,外部pipe理无法识别

接受答案的变化

setuptools代替distutilsimport解决了我的问题:

 from setuptools import setup from setuptools.command.install import install