How to import a module from sub directory

2019-04-12 14:19发布

问题:

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

回答1:

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:

from aname import print_func

with:

from .aname import print_func

Importing a function

To import a function from a given module you can use the from ... import ... statement.

In main.py, replace:

import sub.aname

with:

from sub import print_func


回答2:

from sub import aname
aname.print_func('zz')


回答3:

Probably the most elegant solution is to use relative imports in your submodule sub:

sub.__init__.py

from .aname import print_func

But you also need to import the print_func in main.py otherwise you'll get a NameError when you try to execute print_func:

main.py

from sub import print_func   # or: from sub.aname import print_func

print_func('zz')