有没有办法在 Cython 中为 cimport 提供相当于 Python try 语句的方法?
像这样的东西:
try:
cimport something
except ImportError:
pass
我需要这个来编写一个可以使用或不使用 mpi4py 编译的 Cython 扩展。这在编译语言中是非常标准的,其中 mpi 命令可以放在 #ifdef 和 #endif 预处理器指令之间。我们如何在 Cython 中获得相同的结果?
我试过这个但它不起作用:
try:
from mpi4py import MPI
from mpi4py cimport MPI
from mpi4py.mpi_c cimport *
except ImportError:
rank = 0
nb_proc = 1
# solve a incompatibility between openmpi and mpi4py versions
cdef extern from 'mpi-compat.h': pass
does_it_work = 'Not yet'
实际上,如果 mpi4py 安装正确,但如果
import mpi4py
引发 ImportError,Cython 文件不会编译,我得到错误:
Error compiling Cython file:
------------------------------------------------------------
...
try:
from mpi4py import MPI
from mpi4py cimport MPI
^
------------------------------------------------------------
mod.pyx:4:4: 'mpi4py.pxd' not found
文件setup.py
:
from setuptools import setup, Extension
from Cython.Distutils import build_ext
import os
here = os.path.abspath(os.path.dirname(__file__))
include_dirs = [here]
try:
import mpi4py
except ImportError:
pass
else:
INCLUDE_MPI = '/usr/lib/openmpi/include'
include_dirs.extend([
INCLUDE_MPI,
mpi4py.get_include()])
name = 'mod'
ext = Extension(
name,
include_dirs=include_dirs,
sources=['mod.pyx'])
setup(name=name,
cmdclass={"build_ext": build_ext},
ext_modules=[ext])