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

Python 如何使用简单的安装后脚本扩展distutils?,python,distutils,Python,Distutils,我需要运行一个简单的脚本后,模块和程序已经安装。 我很难找到关于如何实现这一点的直接文档。看起来我需要从distutils.command.install继承,重写一些方法并将此对象添加到安装脚本中。虽然细节有点模糊,但对于这样一个简单的钩子来说似乎需要付出很多努力。有人知道一个简单的方法吗 我在distutils源代码中搜索了一天,了解了足够多的信息,从而生成了一系列自定义命令。它不漂亮,但确实有用 import distutils.core from distutils.command.in

我需要运行一个简单的脚本后,模块和程序已经安装。
我很难找到关于如何实现这一点的直接文档。看起来我需要从distutils.command.install继承,重写一些方法并将此对象添加到安装脚本中。虽然细节有点模糊,但对于这样一个简单的钩子来说似乎需要付出很多努力。有人知道一个简单的方法吗

我在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使用新类,可以使用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},
      ...
      )
希望这能对其他人有所帮助。

我无法让他的答案起作用,我将他的答案调整为类似于扩展区。我想出了这个在我的机器上运行良好的代码

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

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

我在这里尝试接受的答案时出错(可能是因为我在这个特定情况下使用的是Python 2.6,不确定)。“setup.py安装”和“pip安装”都出现这种情况:

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})
sudo python setup.py install
失败并出现错误:setup.cfg中出错:命令“my_install”没有这样的选项“single_version_externally_managed”

更详细地失败,但也有错误:选项--无法识别外部管理的单一版本

对已接受答案的修改 用setuptools替换从distutils导入解决了我的问题:

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

谢谢,乔。我已经发现并发布了类似的答案。不过,您比我更早,所以请欣赏绿色:)可以在
pycparser
的中找到一个示例。作为一名图书馆作者,有人知道这样做的好方法吗?也就是说,为了让每个使用库(安装程序需要)的人都能得到新的安装命令?Joe Wreshnig的回答不起作用,因为
distutils.command.install
是安装模块,他打算扩展的类是
distutils.command.install.install
@cpburnz我修正了另一个答案,因为这很可能是人们首先要尝试的。我一直在研究如何添加自定义命令,但我发现没有任何东西可以用,直到我找到了你的这篇文章!谢谢