importlib 找不到模块

importlib can't find module

cat test.py

from importlib import import_module

bar = import_module('bar', package='project')

ls 项目/

__init__.py  
__init__.pyc
bar.py
bar.pyc

python test.py

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    bar = import_module('bar', package='project')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named bar

列出导入的模块 (sys.modules) 没有显示任何模块 project.

我可以使用 python shell.

导入 bar

有什么想法吗?

它需要在栏前加一个点.. :-(

bar = import_module('.bar', package='project')

import_lib 的文档说

If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod).

因此表达式也可以写成

bar = import_module('..bar',package='project.bar')