簡體   English   中英

ModuleNotFoundError 在 Mac 上的終端中沒有命名模塊

[英]ModuleNotFoundError no module named in Terminal on Mac

我對 python 非常陌生,並且仍在學習它是如何工作的。 我正在為 python class 構建一個小型紙牌游戲,並決定使用 Sublime Text 和 Github 來構建它,以自學它是如何工作的。

(非常小的)目錄如下所示:

/GitHub
├── python-practice
└── war
    ├── __init_.py
    ├── __main__.py
    ├── config
    │   ├── __init__.py
    │   ├── __pycache__
    │   │   ├── card.cpython-38.pyc
    │   │   ├── deck.cpython-38.pyc
    │   │   └── player.cpython-38.pyc
    │   ├── card.py
    │   ├── card.pyc
    │   ├── deck.py
    │   ├── deck.pyc
    │   ├── deck_test.py
    │   └── player.py
    └── game
        ├── __init__.py
        └── logic.py

但是無論我是在終端中使用編譯器還是在 sublime 中使用系統解釋器來運行 logic.py,它總是會返回:

Traceback (most recent call last):
  File "game/logic.py", line 1, in <module>
    import card, deck, player
ModuleNotFoundError: No module named 'card'

...即使它顯然在那里。 我試過from config import card, deck, player也試過import config

將我的所有模塊放在一個文件夾中會很容易和簡單,但我正在嘗試自學目錄,所以我覺得弄清楚這一點很重要。 如何讓我的腳本從同一目錄中與其相鄰的另一個文件夾正確導入模塊? 我錯過了什么?

編輯:從下面的模塊中添加我的代碼。

卡片.py

values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':11, 'Queen':12, 'King':13, 'Ace':14}
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace')

class Card():
    def __init__(self,suit,rank):
        self.suit = suit
        self.rank = rank
        self.value = values[rank]

    def __str__(self):
        return self.rank+" of "+ self.suit

logic.py (未完成,WIP)

from config.card import Card
from config.deck import Deck
from config.player import Player

#Game setup

player_one = player.Player("One")
player_two = player.Player("Two")

new_deck = deck.Deck()
new_deck.shuffle()


for x in range(26):
    player_one.add_cards(new_deck.deal_one())
    player_two.add_cards(new_deck.deal_one())

game_on = True 

round_num = 0 

while game_on:

    

    if len(player_one.all_cards) == 0:
        print('Player One, out of cards! Player Two Wins!')
        game_on = False
        break
    elif len(player_two.all_cards) == 0:
        print('Player Two, out of cards! Player One Wins!')
        game_on = False
        break
    else:
        round_num+=1
    print(f'Round {round_num}')

    #NEW ROUND
    player_one_cards = []
    player_one_cards.append(player_one.remove_one())
    
    player_two_cards = []
    player_two_cards.append(player_two.remove_one())



    pass

像這樣的東西應該工作:

import sys
from pathlib import Path
sys.path.append(str(Path('.').absolute().parent))

from config.card import Card
from config.deck import Deck
from config.player import Player

這基本上允許您從父目錄導入東西,這是您需要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM