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?
2 Answers 2
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')
3 Comments
from . import f, g, i get an ImportError which says cannot import f from __main__ and when i do from .. import f, g i get an ValueError which says attempted relative import beyond top-level packageI 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.
gfromf2when it don't containsg?