如何使用 import lib.import_module 在 Python 中导入模块

我试图在 Python 2.7.2中使用 importlib.import_module,但遇到了这个奇怪的错误。

考虑下面的 dir 结构:

a
|
+ - __init__.py
- b
|
+ - __init__.py
- c.py

a/b/__init__.py代码如下:

import importlib


mod = importlib.import_module("c")

(实际代码 "c"有一个名称。)

尝试 import a.b时,会产生以下错误:

>>> import a.b
Traceback (most recent call last):
File "", line 1, in
File "a/b/__init__.py", line 3, in
mod = importlib.import_module("c")
File "/opt/Python-2.7.2/lib/python2.7/importlib/__init__.py", line 37, in   import_module
__import__(name)
ImportError: No module named c

我错过了什么?

谢谢!

189283 次浏览

For relative imports you have to:

  • a) use relative name
  • b) provide anchor explicitly

    importlib.import_module('.c', 'a.b')
    

Of course, you could also just do absolute import instead:

importlib.import_module('a.b.c')

I think it's better to use importlib.import_module('.c', __name__) since you don't need to know about a and b.

I'm also wondering that, if you have to use importlib.import_module('a.b.c'), why not just use import a.b.c?

And don't forget to create a __init__.py with each folder/subfolder (even if they are empty)