使用setuptools实现pip install时执行指定脚本
简单说,就是重新实现一个安装类,然后让setuptools在安装时调用我们的这个安装类。为了保留原生的安装类中的方法,我们直接继承setuptools中的安装类,然后重写其中的run方法即可:
from setuptools.command.install import install
class CustomInstallCommand(install):
"""Customized setuptools install command"""
def run(self):
install.run(self)
YOUR_FUNCTION() # Replace with your code
然后将setup函数中的cmdclass的“install”置为上面重写的安装类:
setuptools.setup(
...
,
cmdclass={
'install': CustomInstallCommand,
},
)
此外,需要注意的是,如果希望将package上传至PyPI,别人pip install时也能执行你的脚本,则必须要使用源码打包的方式,即:
python setup.py sdist
而不能是:
python setup.py sdist bdist_wheel
因为后者在安装时并不会再去执行setup.py(这种方式可以理解为在上传package时将已经执行过setup.py的结果打包上传了)。

Comments