简体   繁体   English

将类导入另一个文件夹

[英]Importing a class in another folder

I have a problem with python directories. 我的python目录有问题。

I have structure like: 我有这样的结构:

  • python 蟒蛇
    • modules 模块
      • algorithms 算法
        • cyphers cyphers
          • morse.py morse.py
    • tests 测试
      • algorithms 算法
        • cyphers cyphers
          • test_morse.py test_morse.py

When I try to import module in test I get a module not found error. 当我尝试在测试中导入模块时,出现模块未找到错误。 I am trying to import like: 我试图像这样导入:

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 *

I have also init files in all directories. 我还在所有目录中都有init文件。 I am trying to run tests like: 我正在尝试运行以下测试:

> python -m unittest discover ./tests

It is customary to use relative imports 通常使用相对进口

from ....modules.algorithms.ciphers.morse import *

This ensures that you import the right Morse file, otherwise you risk importing some module named Morse that you've installed. 这样可以确保您导入正确的Morse文件,否则就有可能导入已安装的名为Morse的模块。

Here's two examples to illustrate relative imports, say you have a file named simulation.py that has the line 这是两个说明相对导入的示例,假设您有一个名为Simulation.py的文件,其中有一行

from .animals import Herbivore

In it. 在里面。 This will import the Herbivore class from a file in the same directory as the simulation.py file 这将从与Simulation.py文件位于同一目录的文件中导入Herbivore类

Now imagine that you are a folder named tests, in this folder you have a file named test_animals.py, which has the line 现在,假设您是一个名为tests的文件夹,在此文件夹中有一个名为test_animals.py的文件,其中包含以下行

from ..animals import Herbivore

This will import the Herbivore class from a file named animals.py located in the folder above the tests folder. 这将从位于tests文件夹上方的文件夹中的名为animals.py的文件导入Herbivore类。

Finally, note that (at least for Python 3.6) can't run a file that uses relative imports, only import it. 最后,请注意(至少对于Python 3.6)不能运行使用相对导入的文件,而只能导入它。

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

from modules.algorithms.cyphers import morse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM