Python ImportError loading module within subfolder

こ雲淡風輕ζ 提交于 2019-12-08 03:24:13

问题


I have the following structure

abc/
    __init__.py
    settings.py
    tests/
       __init__.py
       test.py

in test.py, I am getting an ImportError for

#test.py
import abc.settings

回答1:


You have two ways.

Firstly, by setting the path variable

import os
import sys
sys.path.insert(0, <Complete path of abc>)

Or by using relative imports.




回答2:


The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

you need to add your root directory to sys.path :

import sys
sys.path.append('path_of_root')

Aldo '..'+sys.path[0] can give you the path of abc directory !



来源:https://stackoverflow.com/questions/27494064/python-importerror-loading-module-within-subfolder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!