繁体   English   中英

导入 Cython.pyd 文件时未找到模块错误

[英]Module not found error when importing a Cython .pyd file

我知道这似乎是一个重复的问题,但我真的找不到我做错了什么......我写了一个 .pyx 文件以便用 cython 将它编译成 a.pyd 。 长话短说,它可以很好地编译我的文件并创建一个 .pyd 文件。 但是,当我尝试导入 that.pyd 文件时,我收到一条错误消息,提示没有名为“name_of_module”的模块。 请注意,这是我第一次尝试 cython ......

我在 windows 10 上使用 venv 和 python3.9。我安装了 cython 和 minGW。 要将其编译为 .pyd 文件,我暗示在与 .pyx 文件相同的目录中键入命令提示符:

python setup.py build_ext --inplace

这是我的 setup.py 文件,用于对 my.pyx 文件进行cythonize:

from setuptools import setup, Extension
from Cython.Build import cythonize

extensions = [Extension('negamax_cy', ['negamax_cy.pyx'])]
setup(ext_modules=cythonize(extensions, language_level=3))

这是 my.pyx 文件:

from connect4.constants import COLS, ROWS
from .position import Position

cdef int COLUMN_ORDER[7]
cdef int x
for x in range(COLS):
    COLUMN_ORDER.append(COLS // 2 + (1 - 2 * (x % 2)) * (1 + x) // 2)


cpdef int negamax(pos, int depth, int alpha, int beta):
    if pos.can_win():   # Check if current player can win this move
        return 1000 - pos.moves*2

    cdef long next_move = pos.possible_non_loosing_moves()
    if next_move == 0:              # Check for moves which are not losing moves
        return -1000 + pos.moves    # If we have 2 or more forcing moves we lose

    if depth == 0:  # Check if we have reached max depth
        return 0

    if pos.moves == ROWS * COLS:  # Check for a draw game
        return 0

    cdef int col = 0
    for col in COLUMN_ORDER[col]:
        if next_move & Position.column_mask(col):
            pos_cp = Position(position=pos)
            pos_cp.play_col(col)
            score = -negamax(pos_cp, depth - 1, -beta, -alpha)

            if score >= beta:
                return score
            alpha = max(alpha, score)

    return alpha

我的项目结构如下(我正在尝试用 pygame 中的 AI 做一个 connect4 游戏):

connect4
   /venv
   /ai
     __init__.py
     setup.py
     file_where_pyd_is_imported.py
     negamax_cy.pyx
     negamax_cy.pyd
     negamax_cy.c
   /connect4
     __init__.py
     other_files.py
__init__.py
main.py

注意 main.py 导入 file_where_pyd_is_imported.py

当我导入时,我只需输入:

import negamax_cy

这是我得到的错误:

Traceback (most recent call last):
  File "D:\Users\dalla\Documents\Coding Projects\python\games\connect4\main.py", line 5, in <module>
    from ai.negamax import mp_best_move, best_move, print_avg
  File "D:\Users\dalla\Documents\Coding Projects\python\games\connect4\ai\negamax.py", line 7, in <module>
    import negamax_cy
ModuleNotFoundError: No module named 'negamax_cy'

正如我所说,我不知道出了什么问题。 也许它与我的项目结构或其他东西有关,或者我的 setup.py 文件,但我不确定......如果有人有想法让我知道。

事实证明我真的很愚蠢,在python3中我必须像这样上传:

from . import negamax_cy

很抱歉浪费了任何人的时间...

暂无
暂无

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

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