python 中通过定义__init__.py可以将一个普通的文件夹变成一个python 包,python 包中含有各种模块,如果要引用的话,有时会找不到路径,这时可以通过sys.path.append('包名'),将包的路径导入python的路径搜索中。另外方法就是使用importlib下的import_module()函数。这个函数有两种导入方式,其中一种是绝对导入,一种是相对导入,相对导入需要注意加入package参数。
def import_module(name, package=None):
"""Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
"""
level = 0
if name.startswith('.'):
if not package:
msg = ("the 'package' argument is required to perform a relative "
"import for {!r}")
raise TypeError(msg.format(name))
for character in name:
if character != '.':
break
level += 1
return _bootstrap._gcd_import(name[level:], package, level)
其中importlib模块还有很多其他功能,比如 1模块导入检查,2 从源代码导入。这些目前还没有遇到。
参考文献:
Python中动态导入对象importlib.import_module()的使用_edward_zcl的博客-CSDN博客_importlib.import_module