I failed to import a module from sub directory in python. Below is my project structure.
./main.py
./sub
./sub/__init__.py
./sub/aname.py
when I run python main.py
, I got this error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
import sub.aname
File "/Users/dev/python/demo/sub/__init__.py", line 1, in <module>
from aname import print_func
ModuleNotFoundError: No module named 'aname'
I don't know it failed to load the module aname
. Below is the source code:
main.py
:
#!/usr/bin/python
import sub.aname
print_func('zz')
sub/__init__.py
:
from aname import print_func
sub/aname.py
:
def print_func( par ):
print ("Hello : ", par)
return
I am using python 3.6.0 on MacOS
There are several mistakes in your Python scripts.
Relative import
First, to do relative import, you must use a leading dots (see Guido's Decision about Relative Imports syntax).
In
sub/__init__.py
, replace:with:
Importing a function
To import a function from a given module you can use the
from ... import ...
statement.In
main.py
, replace:with:
Probably the most elegant solution is to use relative imports in your submodule
sub
:sub.__init__.py
But you also need to import the
print_func
inmain.py
otherwise you'll get aNameError
when you try to executeprint_func
:main.py