简体   繁体   中英

ModuleNotFoundError: No module named 'utils': How do I change the parent directory looked at by Import

I think I know what the issue is here but I don't know how to approach fixing it. This is the current structure I have in my project directory:

└── src
    ├── utils
       └── utils.py
    ├── comparator
       └── comparatorclass.py

In my comparatorclass.py I have the following import statements:

from utils.logging_service import LoggingService
from utils.utils import Utils

When I run comparatorclass.py, I get the error

Traceback (most recent call last):
  File "comparator_gui.py", line 11, in <module>
    import comparatorclass
  File "/Users/sidu/Desktop/aaababa/src/comparator/comparatorclass.py", line 16, in <module>
    from utils.logging_service import LoggingService
ModuleNotFoundError: No module named 'utils'

Of course, I'm pretty sure what's happening is that the comparatorclass.py is looking for the utils directory within the comparator directory when in fact it is one layer above that. The code works when I have a structure like this:

└── src
    ├── utils
       └── utils.py
    ├── comparatorclass.py

This makes sense because now it is able to find the utils directory within the same parent, src. My question is how do I get it to work with the first scenario? I need a way to change what parent directory the import statement looks at.

I fixed the problem by adding the following line before importing the utilities:

sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..'))  

from utilities.logging_service import LoggingService
from utilities.comparator_utils import Utils

I don't know if this is the correct solution, but it did solve the problem for me.

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