LChampo
LChampo

Reputation: 77

Python - Module Not Found Error

I have this structure:

F
  f1
    __init__.py
    f.py
    g.py
  f2
    __init__.py
    h.py

f2.__init__.py:

from f1 import f, g

f2.h.py:

from f2 import f, g

f2.py is a __main__ file. When i run f2, I get the error

ModuleNotFoundError: No module named 'f2'

How can I fix that?

Upvotes: 0

Views: 6503

Answers (2)

Jirka
Jirka

Reputation: 1146

if you are running main in the f2.h.py directly the interpreter does not seem the parent path to F.

An option is to use relative imports which are different for Python 2/3. For example, add F.__init__.py file, then chnage F.f2.__init__.py to from ..f1 import f, g and finaly in F.f2.h.py import as from F.f2 import f, g.

Another option is adding the path to the parent destination:

import os, sys
sys.path += [os.path.abspath('..')]

from f2 import f, g

if __name__ == '__main__':
    print('hello')

Upvotes: 1

LChampo
LChampo

Reputation: 77

I fix it. As Jirka B. said, the problem was i run the code directley from the interpreter. After doing what should be done, everything works as i like. Thx guys.

Upvotes: 0

Related Questions