簡體   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