![](/img/trans.png)
[英]Handling logger directory when importing a class into another file in child folder
[英]Importing a class in another folder
我的python目錄有問題。
我有這樣的結構:
當我嘗試在測試中導入模塊時,出現模塊未找到錯誤。 我試圖像這樣導入:
parent_dir_name = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(parent_dir_name + "/../../../")
from modules.algorithms.cyphers.morse import *
我還在所有目錄中都有init文件。 我正在嘗試運行以下測試:
> python -m unittest discover ./tests
通常使用相對進口
from ....modules.algorithms.ciphers.morse import *
這樣可以確保您導入正確的Morse文件,否則就有可能導入已安裝的名為Morse的模塊。
這是兩個說明相對導入的示例,假設您有一個名為Simulation.py的文件,其中有一行
from .animals import Herbivore
在里面。 這將從與Simulation.py文件位於同一目錄的文件中導入Herbivore類
現在,假設您是一個名為tests的文件夾,在此文件夾中有一個名為test_animals.py的文件,其中包含以下行
from ..animals import Herbivore
這將從位於tests文件夾上方的文件夾中的名為animals.py的文件導入Herbivore類。
最后,請注意(至少對於Python 3.6)不能運行使用相對導入的文件,而只能導入它。
如果使用__init__.py
將目錄標記為模塊,則應該能夠通過導入模塊
from modules.algorithms.cyphers import morse
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.