ModuleNotFoundError: No module named '__main__.xxx'; '__main__' is not a package問題

問題描述

今天寫代碼時碰到一個有趣的報錯:"ModuleNotFoundError: No module named '__main__.xxx'; '__main__' is not a package"
問題發生在包內引用中。我的目錄結構如下:
在這裏插入圖片描述
Wheel.py中定義了一個Wheel類,在Parser.py中我想導入這個類,於是寫了這樣一句:

line7:	from .Wheel import Wheel

Parser.py中點擊Run之後,解釋器提示以下錯誤:
在這裏插入圖片描述

根源定位

經過一番百度,在Stack Overflow中找到了答案——相對導入只有在父模塊已經在當前運行環境中被導入過纔有用
在這裏插入圖片描述
對於這一問題,官方文檔intra-package-references也給出瞭解釋:

Note that relative imports are based on the name of the current module. Since the name of the main module is always “main”, modules intended for use as the main module of a Python application must always use absolute imports.

這裏揭示了報錯的緣由,相對導入基於當前模塊的名稱,因爲主模塊總被命名爲"__main__"。當我們從主模塊啓動時,Python就識圖用"__main__"替換".",於是那句話實際便成了from __main__.Wheel import Wheel,這當然是找不到的。

解決辦法

有兩種:
一、使用絕對導入,這種絕逼不會錯(也是官方文檔給出的辦法),即:

	from Core.Wheel import Wheel

二、保留當前寫法,但不再以當前模塊爲主模塊啓動應用,例如:

	在Core同級目錄下定義一個外部py文件,並在其中引入要引用的模塊,此時目錄變成:
	|---run.py
	|---Core
		|---__init__.py
		|---Wheel.py
		|---Parser.py

run.py中我們引入Parser類,因爲此時的主模塊變成了run,並且父模塊已經被引入過,所以不再報錯。

	# run.py
	from Core import Parser
	if __name__=='__main__':
		t = Parser.Parser()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章