【问题标题】:Why doesn't setup_requires work properly for numpy?为什么 setup_requires 不能正常用于 numpy?
【发布时间】:2014-03-03 13:50:36
【问题描述】:

我想创建一个 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} 上测试了这个,在最近版本的 setuptools 上使用和不使用 virtualenv。

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

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

【问题讨论】:

    标签: python numpy setuptools


    【解决方案1】:

    发现,通过检查 numpy/__init__.py 内部的 __NUMPY_SETUP__ 会阻止正确初始化 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
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-16
      • 2019-01-04
      • 2020-09-03
      • 2016-10-10
      • 2016-10-24
      • 2017-02-27
      相关资源
      最近更新 更多