如果设计一个 setup.py 并且有可以通过两个不同模块来满足的要求,即只需要安装两个模块中的一个,我如何install_requires在行中表达?例如setup.py看起来像这样:
setup(
name='my_module',
version='0.1.2',
url='...',
...,
install_requires=['numpy', 'tensorflow']
)
Run Code Online (Sandbox Code Playgroud)
执行pip install my_module此操作时,即使安装了tensorflow-gpu(也可以满足要求,但不会,因为它的命名不同),也会将tensorflow (CPU) 作为要求安装。
我可以做这样的事情:
install_requires=['numpy', 'tensorflow' or 'tensorflow-gpu']
Run Code Online (Sandbox Code Playgroud)
extras_require您的设置功能中需要一个:
extras_require = {
'gpu': ['tensorflow-gpu'],
'cpu': ['tensorflow']
},
Run Code Online (Sandbox Code Playgroud)
然后可以安装:
pip install your_package[gpu]或者pip install your_package[cpu]
这setup.py只是另一个 python 脚本,因此您可以在其中放入任何逻辑来确定正确的设置参数。例如,您可以检查是否tensorflow或tensorflow_gpu已安装并修改安装在运行DEPS列表:
from pkg_resources import DistributionNotFound, get_distribution
from setuptools import setup
def get_dist(pkgname):
try:
return get_distribution(pkgname)
except DistributionNotFound:
return None
install_deps = []
if get_dist('tensorflow') is None and get_dist('tensorflow_gpu') is None:
install_deps.append('tensorflow')
setup(
...
install_requires=install_deps,
)
Run Code Online (Sandbox Code Playgroud)
但是请注意,一旦您开始将代码放入安装脚本中执行安装时执行任何操作的代码中,您就不能再分发轮子了,因为轮子不提供setup.py. 而是在构建时执行一次。源分布将很好地服务:
from pkg_resources import DistributionNotFound, get_distribution
from setuptools import setup
def get_dist(pkgname):
try:
return get_distribution(pkgname)
except DistributionNotFound:
return None
install_deps = []
if get_dist('tensorflow') is None and get_dist('tensorflow_gpu') is None:
install_deps.append('tensorflow')
setup(
...
install_requires=install_deps,
)
Run Code Online (Sandbox Code Playgroud)
tensorflow如果未安装,则安装生成的源 tar 将拉取:
$ python setup.py sdist
running sdist
running egg_info
...
creating dist
Creating tar archive
removing 'mypkg-0.0.0' (and everything under it)
Run Code Online (Sandbox Code Playgroud)