简体   繁体   English

尝试在 setup.py 中指定的同一包中安装 Python 扩展模块 (Cython) 时出现 ModuleNotFound

[英]ModuleNotFound when trying to install Python Extension Module (Cython) inside the same package specified in setup.py

I have a Cython extension module for a Python project I want to install to the same namespace as the project on installation.我有一个 Python 项目的 Cython 扩展模块,我想安装到与安装项目相同的命名空间。 When I try to specify in the extension to install it inside the package itself, it can't be found and imported.当我尝试在扩展中指定将其安装在包本身中时,无法找到并导入它。 If I specify the extension goes in the root of the Python namespace, it works fine, but it's not in the module namespace I want.如果我指定扩展名在 Python 命名空间的根目录中,它可以正常工作,但它不在我想要的模块命名空间中。 How do I get the Extension Module to be importable from the same namespace as the package itself?如何从与包本身相同的命名空间导入扩展模块?

I've made a simple test case for this question.我为这个问题做了一个简单的测试用例。

Folder Structure:文件夹结构:

mypkg
├── foo
│   ├── __init__.py
│   └── barCy.pyx
└── setup.py

The .barCy.pyx file: .barCy.pyx文件:

cpdef long bar():
    return 0

The setup.py code: setup.py代码:

import distutils.extension
from Cython.Build import cythonize

from setuptools import setup, find_packages

extensions = [distutils.extension.Extension("foo.bar",
                                            ['foo/barCy.pyx'])]
setup(
        name='foo',
        packages=find_packages(),
        ext_modules=cythonize(extensions),
        )

The __init.py__ is empty. __init.py__是空的。

I want to be able to do:我希望能够做到:

>>> import foo.bar as bar
>>> bar.bar()
0

Instead, I get相反,我得到

>>> import foo.bar as bar
ModuleNotFoundError: No module named 'foo.bar'

If I were to change the Extension("foo.bar",... to Extension("bar",... , then I can do import bar like it were a top level package. Although that is the expected behavior, it's not what I want as I only want this extension module to be accessible through the foo namespace.如果我将Extension("foo.bar",...更改为Extension("bar",... ,那么我可以像顶级包一样import bar 。虽然这是预期的行为,但它是不是我想要的,因为我只希望可以通过foo命名空间访问此扩展模块。

My Python interpreter was being run from the same folder as the setup.py script, so doing import foo was importing the local package, rather than the one installed in Python interpreter's site-packages directory.我的 Python 解释器是从与setup.py脚本相同的文件夹中运行的,因此执行import foo是导入本地包,而不是安装在 Python 解释器的site-packages目录中site-packages Because they have the same folder structure, the local directory was chosen as the superseding imported package.由于它们具有相同的文件夹结构,因此选择本地目录作为替代的导入包。

Do testing/running from a different folder than the source.从与源不同的文件夹进行测试/运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM