最后通过修改setup.py
为执行安装的命令添加了其他处理程序来解决。
setup.py
这样做的一个示例可能是:
import os
from setuptools import setup
from setuptools.command.install import install
import subprocess
def get_virtualenv_path():
"""Used to work out path to install compiled binaries to."""
if hasattr(sys, 'real_prefix'):
return sys.prefix
if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix:
return sys.prefix
if 'conda' in sys.prefix:
return sys.prefix
return None
def compile_and_install_software():
"""Used the subprocess module to compile/install the C software."""
src_path = './some_c_package/'
# compile the software
cmd = "./configure CFLAGS='-03 -w -fPIC'"
venv = get_virtualenv_path()
if venv:
cmd += ' --prefix=' + os.path.abspath(venv)
subprocess.check_call(cmd, cwd=src_path, shell=True)
# install the software (into the virtualenv bin dir if present)
subprocess.check_call('make install', cwd=src_path, shell=True)
class CustomInstall(install):
"""Custom handler for the 'install' command."""
def run(self):
compile_and_install_software()
super().run()
setup(name='foo',
# ...other settings skipped...
cmdclass={'install': CustomInstall})
现在,当python setup.py install
被调用时,将使用自定义CustomInstall
类,然后在正常安装步骤运行之前编译并安装软件。
您也可以对感兴趣的任何其他步骤执行类似操作(例如build / develop / bdist_egg等)。
另一种选择是使compile_and_install_software()
函数成为的子类setuptools.Command
,并为其创建完整的setuptools命令。
这比较复杂,但是可以让您执行一些操作,例如将其指定为另一个命令的子命令(例如避免执行两次),并在命令行上将自定义选项传递给它。