20

我想为一个 python 包创建一个 setup.py 脚本,其中包含几个依赖于 cython 和 f2py 的子模块。我曾尝试使用 setuptools 和 numpy.distutils,但到目前为止都失败了:

使用设置工具

我可以使用 setuptools 编译我的 cython 扩展(并为包的其余部分创建安装)。但是,我一直无法弄清楚如何使用 setuptools 来生成 f2py 扩展。经过大量搜索,我只发现了类似这样的相当老的消息,指出 f2py 模块必须使用 numpy.distutils 编译。

使用 numpy.distutils

我可以使用 numpy.distutils 编译我的 f2py 扩展(并为包的其余部分创建安装)。但是,我一直无法弄清楚如何让 numpy.distutils 编译我的 cython 扩展,因为它最近总是尝试使用 pyrex 来编译它(而且我正在使用特定于 cython 的扩展)。我已经进行了搜索以弄清楚如何为 cython 文件获取 numpy.distutils,并且 - 至少在一年前 - 他们建议将猴子补丁应用于 numpy.distutils。似乎应用这样的猴子补丁也限制了可以传递给 Cython 的选项。

我的问题是:为依赖于 f2py 和 cython 的包编写 setup.py 脚本的推荐方法是什么?对 numpy.distutils 应用补丁真的是要走的路吗?

4

2 回答 2

6

您可以在 setup.py 中单独调用每个,如
http://answerpot.com/showthread.php?601643-cython%20and%20f2py

# Cython extension
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

setup(
  ext_modules = [Extension( 'cext', ['cext.pyx'] )],
  cmdclass = {'build_ext': build_ext},
  script_args = ['build_ext', '--inplace'],
)

# Fortran extension
from numpy.distutils.core import setup, Extension
setup(
  ext_modules = [Extension( 'fext', ['fext.f90'] )],
)

您的调用上下文(我认为他们调用此命名空间,不确定)
必须更改当前对象 Extension 和函数
setup() 是什么。

第一个 setup() 调用,它是 distutils.extension.Extension
和 distutils.core.setup()

第二个 setup() 调用,它是 numpy.distutils.core.Extension
和 numpy.distutils.core.setup()

于 2011-12-14T19:42:34.367 回答
3

事实证明这不再是真的。和(至少是版本)可以使用 C、Cythonsetuptools和f2py 进行扩展。唯一需要注意的是,要编译 f2py 模块,必须始终同时使用和函数。但仍可用于安装(例如,允许安装带有 的开发人员版本)。distutilsnumpynumpy.distutilssetupExtensionsetuptoolspython setup.py develop

distutils独占使用,请使用以下内容:

from numpy.distutils.core import setup
from numpy.distutils.extension import Extension

要使用setuptools,您需要在导入之前导入它distutils

import setuptools

然后其余的代码是相同的:

from numpy import get_include
from Cython.Build import cythonize

NAME = 'my_package'
NUMPY_INC = get_include()
extensions = [
    Extension(name=NAME + ".my_cython_ext", 
              include_dirs=[NUMPY_INC, "my_c_dir"]
              sources=["my_cython_ext.pyx", "my_c_dir/my_ext_c_file.c"]),
    Extension(name=NAME + ".my_f2py_ext", 
              sources=["my_f2py_ext.f"]),
]
extensions = cythonize(extensions)
setup(..., ext_modules=extensions)

显然,您需要将所有其他内容都放入setup()通话中。在上面我假设您将 numpy 与 Cython 一起使用,以及将位于的外部 C 文件 ( my_ext_c_file.c) my_c_dir/,并且该f2py模块只是一个 Fortran 文件。根据需要进行调整。

于 2017-01-27T14:21:55.533 回答