简体   繁体   中英

Python: No module found even though it exists in directory

Consider I have the following project structure:

+PROJECT
|  +models
|  |  =__init__.py
|  |  =client.py
|  |  =config.py
|
|  +tests
|  | =__init__.py
|  | =example.py
|  | =example_two.py
|
|  README.md
|  requirements.txt

When I try to import a class from client and a variable from config into example.py, like so:

from models.config import var 
from models.client import Class

I receive a ModuleNotFound Error for both import statements. I know this question has been asked plenty of times before but those solutions don't resolve my issue. I tried placing client and config in the same level as the test folder. However, I received the same issue. It would be great If someone can help me work through this issue.

You will need to do a relative import ( PEP-328 ), but according to this guide , you can only go up until the level where you launched the script from, which is the tests directory in you case.

So you'll either have to add the model directory to the path, or add the source folder of your project to a .pth file in your site-packages as shown here

Three possibilities come to my mind:

  • The module just works for certain python versions (eg 3.5 but not 3.6).
  • The path where your module is currently located does not appear in sys.path.
  • The class you want to use must be specified while importing the module because it is not specified in the __init__.py of the module itself.

As far as I can tell, only the first option might cause your problem.
Nevertheless I would make a quick check with

import sys
sys.path

and in case that the correct path is really missing..

sys.path.append('PathToModule')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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