为什么setup_requires不适合numpy?

问题描述 投票:11回答:1

我想创建一个setup.py文件,该文件自动将构建时依赖性解析为numpy(用于编译扩展)。我的第一个猜测是使用setup_requires和子类命令类来导入numpy模块:

from setuptools import setup, Extension
from distutils.command.build import build as _build

class build(_build):
    def run(self):
        import numpy
        print(numpy.get_include())
        _build.run(self)

setup(
    name='test',
    version='0.0',
    description='something',
    cmdclass={'build':build},
    setup_requires=['numpy'],
)

现在,运行python setup.py build成功编译numpy但随后失败(在build.run内):

AttributeError: 'module' object has no attribute 'get_include'

但是,如果再次运行相同的命令,该命令现在成功(并且不需要重新编译numpy)。

我已经在python {2.6,2.7,3.3}上使用和不使用virtualenv在最新版本的setuptools上进行了测试。

我见过一个workaround using pkg_resources.resource_filename似乎工作得很好,如果我们想要的只是include目录。编辑:只适用于python2!

但是,我现在很好奇。使用setup_requires有什么警告?可能是因为numpy无法正常工作的原因是什么?对于一些更简单的模块,它似乎没有问题。

python numpy setuptools
1个回答
11
投票

想通过检查__NUMPY_SETUP__中的numpy/__init__.py来阻止numpy模块的正确初始化:

if __NUMPY_SETUP__:
    import sys as _sys
    _sys.stderr.write('Running from numpy source directory.\n')
    del _sys
else:
    # import subodules etc. (main branch)

安装后,setuptools不会重置此全局状态。以下作品:

...
def run(self):
    __builtins__.__NUMPY_SETUP__ = False
    import numpy
    ...
© www.soinside.com 2019 - 2024. All rights reserved.