我知道这可能看起来像是一个重复的问题,但我真的找不到我做错了什么......我编写了一个 .pyx 文件,以便使用 cython 将其编译为 .pyd。长话短说,它可以很好地编译我的文件并创建一个 .pyd 文件。但是,当我尝试导入该 .pyd 文件时,出现错误,提示没有名为:“name_of_module”的模块。请注意,这是我第一次尝试 cython...
我在 Windows 10 上将 venv 与 python3.9 一起使用。我将 cython 与 minGW 一起安装。要将其编译为 .pyd 文件,我意味着在与 .pyx 文件相同的目录中输入命令提示符:
python setup.py build_ext --inplace
这是我的 setup.py 文件,用于 cythonize 我的 .pyx 文件:
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))
这是我的 .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 中使用 A.I. 做一个 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