我有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
习惯使用relative imports
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