【问题标题】:Another "ImportError: cannot import name"另一个“ImportError:无法导入名称”
【发布时间】:2017-08-02 19:44:41
【问题描述】:

我有四个文件:menu.pynotebook.py__init__.pytest.py,它们按照 @afaq 的建议排列。

我的notebook.py

class Note:
    def __init__(self,memo,tag = ''):
        self.memo = memo
        self.tag = tag

    def match(self,filter):
        '''determine if this note matches the filter text, return
        true if match, false if not'''
        return filter in self.memo or filter in self.tag

class Notebook:
    def __init__(self):
        '''ininitalize a notebook with empty list'''
        self.note = []

    def search(self,filter):
        '''Find all notes that match the given filter string.'''
        return [note for note in self.note if note.match(filter)]

还有menu.py:(已编辑)

import sys

from .notebook import Note, Notebook

class Menu:
    '''Display a menu and respond to choices when run.'''
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
            "1": self.search_note,
            "2": self.quit
        }

    def display_menu(self):
        print("""
            Notebook Menu
            1. Search Notes
            2. Quit
            """)

    def run(self):
        '''Display the menu and respond to choices.'''
        while True:
            self.display_menu()
            choice = input("Choice is: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

    def search_note(self):
        '''search for text and display all notes contain it'''
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_note()

    def quit(self):
        print("Bye bye")
        sys.exit(0)

我的__init__.py 是空的

我的test.py

from Notebook.my_notebook.menu import Menu

if __name__ == "__main__":
    Menu().run()

当我运行test.py 时,python 会返回此错误:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    from Notebook.my_notebook.menu import Menu
ModuleNotFoundError: No module named 'Notebook'

我该如何解决这个问题?

【问题讨论】:

  • 笔记本不是全局模块,请阅读stackoverflow.com/questions/1112618/…
  • @Filip:谢谢,我编辑 .notebook 而不是 notebook 并得到了这个新错误。你能帮忙吗?
  • 试试from . import notebook
  • python 返回这个错误Traceback (most recent call last): File "menu.py", line 2, in &lt;module&gt; from . import Note, Notebook ImportError: cannot import name 'Note'
  • 您没有Notebook 包或任何名为my_notebookmenu 的东西。你为什么期待from Notebook.my_notebook.menu import Menu 这样做?你认为 import 语句是如何工作的?

标签: python python-import importerror


【解决方案1】:

在单独的模块中创建if __name__ == "__main__": 调用。尝试执行该模块时不能进行相对导入。

查看Ultimate answer to relative python imports

menu.py

import sys

from .notebook import Note, Notebook

class Menu:
    '''Display a menu and respond to choices when run.'''
    def __init__(self):
        self.notebook = Notebook()
        self.choices = {
            "1": self.search_note,
            "2": self.quit
        }

    def display_menu(self):
        print("""
            Notebook Menu
            1. Search Notes
            2. Quit
            """)

    def run(self):
        '''Display the menu and respond to choices.'''
        while True:
            self.display_menu()
            choice = input("Choice is: ")
            action = self.choices.get(choice)
            if action:
                action()
            else:
                print("{0} is not a valid choice".format(choice))

    def search_note(self):
        '''search for text and display all notes contain it'''
        filter = input("Search for: ")
        notes = self.notebook.search(filter)
        self.show_note()

    def quit(self):
        print("Bye bye")
        sys.exit(0)

您的目录结构应如下所示。

您的包结构应如下所示。

执行器代码如下所示

【讨论】:

  • 谢谢!我会尝试并返回结果。
  • 感谢您的更新。 3分我不是很清楚。首先,在第一张图片中,notbook_menu 是什么?二、__init__.py里面是什么?三、执行者代码的意思是,我将menu.py中的if__name__ ...行删除,对吗?
  • notebook_menu 只是我为您的 python 文件选择的随机包名称。 __init__ 文件使您的文件夹成为 python 包。是的,当您像我在这里一样创建执行程序时,您将不再需要 menu.py 中的if __name__ ...
  • 抱歉图片中notebook_menu的错字。
  • 不用担心错字。我会继续努力,让你知道我得到了什么。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2016-03-31
  • 2014-10-10
  • 2014-09-20
  • 2014-08-28
  • 2014-06-10
  • 2016-05-16
  • 2019-05-25
  • 2017-04-22
相关资源
最近更新 更多