【问题标题】:Cython compile error "is not a valid module name"Cython 编译错误“不是有效的模块名称”
【发布时间】:2017-02-08 00:40:09
【问题描述】:

我试图在 Windows 上编译一个 Cython 文件 (.pyx),这是我刚刚从 .py 保存的文件。这是我的项目目录路径。

c:\..\Project\App\Analyzer\
_init_.py
Few_other_files.py
consolidated_loop_C.pyx
cl_setup.py

这是我的 cl_setup.py

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


setup(
    name = "Consolidated Loop",
    ext_modules = cythonize("consolidated_loop_C.pyx")
)

我使用下面的语句在同一个文件夹中编译。

python cl_setup.py build_ext --inplace

但我收到以下错误。我的猜测是我缺少 cythonize() 的某些参数,试图研究但没有任何运气。

【问题讨论】:

  • 它从你的路径中捡起一个破折号并抱怨它(见stackoverflow.com/questions/32799506/… 相同的问题)。我不太确定它到底为什么这样做。简单的解决方案是重命名目录(但这并不是一个真正合适的解决方案 - 你不应该这样做)。
  • @DavidW 是的,你是对的,它是文件夹名称中的破折号。我现在已重命名该文件夹。谢谢。

标签: python compilation cython


【解决方案1】:

首先,将 setup.py 文件更改为仅使用 distutils

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

setup(
    name = "Consolidated Loop",
    ext_modules = cythonize("consolidated_loop_C.pyx")
)

这是为了方便潜在回复者的调试。

然后,通过一些实验和其他 SO 帖子 Python building cython extension with setup creates subfolder when __init__.py existsThe command `python setup.py build_ext --inplace` always create a new directory

我建议将您的 cython 文件移动到子目录中或删除 __init__.py 文件。后一个问题很可能导致 Python 或 Cython 猜测当前目录的模块名称,因此出现破折号问题。另外,setup.py 文件不能存在于模块目录中,这会造成麻烦。

如果您打算分发或打包您的代码,则更可取的是前一个选项(将文件干净地移动到具有自己的__init__.py 的子目录中,等等)。否则,只需删除 __init__.py 即可。这将使用build_ext --inplace 创建一个本地可用的Python 模块consolidated_loop_C.so

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多