如何在 setup.py 中使用 distutils 或 setuptools 使 cython 扩展可导入(无需在每次导入前附加到 sys.path)?

How to use distutils or setuptools in setup.py to make a cython extention importable (without needing to append to sys.path before every import)?

我有 cython 扩展,我按以下方式安装:

from distutils.core import setup
from Cython.Build import cythonize

setup(ext_modules=cythonize(
    "package.pyx",
    language="c++")
)

当我想导入这个包时,我需要使用以下命令将构建文件夹附加到路径:

import sys
sys.path.append(~/package/build/....)

安装中需要更改哪些内容才能将模块安装到 Linux 中并且无需附加到路径即可导入?

我也愿意使用 setuptools。

试试我的 setup.py 作为模板...这些东西没有很好的记录。这里要记住的一件事是,如果您构建 inplace,您可能必须 from projectname.module import module:

try:
    from setuptools import setup
    from setuptools import Extension
except ImportError:
    from distutils.core import setup
    from distutils.extension import Extension

module = 'MyModuleName' # this assumes your .pyx and your import module have the same names
# ignore the below extra options if you don't need them (i.e. comment out `#`)
ext_modules = [Extension(module, sources=[module + ".pyx"],
              include_dirs=[],
              library_dirs=[], 
              extra_compile_args=[],
              language='c++')]

setup(
    name = module,
    ext_modules = ext_modules,
    cmdclass = {'build_ext': build_ext},
    include_dirs = [np.get_include(), os.path.join(np.get_include(), 'numpy')]
    )