简体   繁体   English

无法从兄弟目录导入模块

[英]Can't import module from sibling directory

I have a Python 3 project that's structured like this: 我有一个Python 3项目,其结构如下:

/project
    __init__.py
    /models
        __init__.py
        my_model.py
        base_model.py
    /tests
        __init__.py
        test.py

In test.py I want to import my_model . test.py我想导入my_model My first attempt was from models import my_model , which threw an ImportError: No module named 'models' . 我的第一次尝试from models import my_model ,它引发了一个ImportError: No module named 'models' This question recommended adding an __init__.py file to each directory, which didn't help. 这个问题建议在每个目录中添加一个__init__.py文件,但没有帮助。 Another post said to modify the path with: 另一篇文章说修改路径:

import sys; import os
sys.path.insert(0, os.path.abspath('..'))

but this throws an error when my_model tries to import from base_model . 但是当my_model尝试从base_model导入时会抛出一个错误。

This seems really straightforward but I'm stumped. 这似乎很简单,但我很难过。 Does anyone have any ideas? 有没有人有任何想法?

在所有地方使用绝对导入: from project.models import my_model ,应该可以在项目的任何地方正常工作,也不需要弄乱路径。

Adding the sibling directory to sys.path should work: 将兄弟目录添加到sys.path应该有效:

import sys, os
sys.path.insert(0, os.path.abspath('../models'))
import my_model

The answer depends on how you launch test.py. 答案取决于你如何启动test.py. The only way I know to do relative imports is to have the file in a package. 我知道做相对导入的唯一方法是将文件放在包中。 For the Python interpreter to know you're in a package is to import it in some way. 对于Python解释器来说,知道你在一个包中是以某种方式导入它。

Use: 使用:

from ..models import my_model

in test.py 在test.py中

And launch the Python Interpreter below the project folder. 并在项目文件夹下面启动Python Interpreter。

You will then be able to import project.tests.test without error. 然后,您将能够无错误地导入project.tests.test。

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

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