【发布时间】:2018-04-22 22:21:44
【问题描述】:
我目前正在处理一个导入 Fortran 模块的 Python 项目。 setup.py 看起来类似
from numpy.distutils.core import Extension
from numpy.distutils.core import setup
ext = Extension(
name = "fortran_module",
sources = ["fortran_module.f90"],
extra_f90_compile_args = ["-some -compile -arguments"]
)
setup(
...,
...,
...,
ext_modules = [ext],
...,
...,
...
)
我目前正在使用pip install -e . 安装它,效果很好。
但有时我需要更改extra_f90_compile_args,我想在安装过程中使用pip 将它们作为命令行参数而不是更改setup.py 文件。例如这样的事情:
pip install -e --compile_args="-O3 -fbacktrace -fbounds-check -fopenmp" .
是否可以通过pip 将命令行参数传递到setup.py 文件中?
与此相关,我还想将不同的设置选项传递给setup.py。例如
pip install -e --setup=setup1 .
或
pip install -e --setup=setup2 .
根据setup1 或setup2 是否通过,我想包含不同的Fortran 源文件并使用不同的extra_f90_compile_args 编译它们。
这可能吗?
编辑:让我们考虑以下示例:Fortran 模块与 OpenMP 并行化。现在我希望用户决定是否并行编译。可能 OpenMP 库不可用,用户需要编译串行版本。
我的setup.py 现在如下所示
from numpy.distutils.core import Extension
from numpy.distutils.core import setup
import os
from setuptools.command.install import install as _install
extra_f90_compile_args = ""
extra_link_args = ""
class install(_install):
user_options = _install.user_options + [('build=', None, None)]
def initialize_options(self):
_install.initialize_options(self)
self.build = None
def finalize_options(self):
_install.finalize_options(self)
def run(self):
global extra_f90_compile_args
global extra_link_args
if(self.build == "parallel"):
extra_f90_compile_args += "-fopenmp"
extra_link_args += "-lgomp"
os.makedirs("~/test/")
_install.run(self)
ext = Extension(
name="test_module.fortran_module",
sources=["test_module/fortran_module.f90"],
extra_f90_compile_args=[extra_f90_compile_args],
extra_link_args=[extra_link_args]
)
setup(
name="test_module",
packages=["test_module"],
ext_modules=[ext],
cmdclass={'install': install}
)
如果我安装这个
pip install . --install-option="--build=parallel"
它正在执行if-block 中的代码。我创建了test/ 目录只是为了检查这一点。如果build 未给出或与parallel 不同,则不会创建test/ 目录。
但是,代码不是用 OpenMP 编译的。我认为这是因为Extension 对象是在调用setup() 之前创建的,其中参数被评估。我想先评估参数,然后根据参数创建Extension 对象,然后调用setup()。
我该怎么做?
【问题讨论】:
-
我知道这个问题和其他几个问题。但是,我无法让它在我的情况下工作。见编辑。
-
在添加的代码中存在缩进问题——方法没有正确缩进。请修复。
-
已修复。我的问题是我想评估
setup.py文件中的参数之前setup()被调用。 -
啊哈,我明白了——您需要从全局变量中评估
ext。