在另一个文件夹中导入一个类

问题描述 投票:0回答:2

我有python目录的问题。

我有这样的结构:

  • 蟒蛇 模块 算法 cyphers morse.py 测试 算法 cyphers test_morse.py

当我尝试在测试中导入模块时,我得到一个模块未找到错误。我想导入如下:

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
python python-2.7
2个回答
1
投票

习惯使用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)无法运行使用相对导入的文件,只能导入它。


0
投票

如果使用__init__.py将目录标记为模块,则应该只能通过导入模块

from modules.algorithms.cyphers import morse
© www.soinside.com 2019 - 2024. All rights reserved.