Python3:导入和 importlib.import_module 之间的不同行为?
Python3: different behaviour between import and importlib.import_module?
我无法动态导入我在代码中导入没有问题的模块,但我不知道为什么。
我有以下内容:
> ls lib
__init__.py main.py
初始化文件为空。以下作品:
> python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import lib.main
>>> lib.main.sayyay()
yay
以下不起作用:
> python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import importlib
>>> importlib.import_module("lib.main")
<module 'lib.main' from '/some/path/lib/main.py'>
>>> lib.main.sayyay()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'lib' is not defined
我确实阅读了 importlib 文档以及此处关于 SO 的几个答案,例如 How to import a module in Python with importlib.import_module and Dynamically import a method in a file, from a string
但是我错过了什么?
import_module
returns 导入的模块。
因此,你需要给导入的模块起一个名字,就像lib.main
一样使用它
>>> lib_main = importlib.import_module("lib.main")
>>> lib_main.sayyay()
我无法动态导入我在代码中导入没有问题的模块,但我不知道为什么。
我有以下内容:
> ls lib
__init__.py main.py
初始化文件为空。以下作品:
> python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import lib.main
>>> lib.main.sayyay()
yay
以下不起作用:
> python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import importlib
>>> importlib.import_module("lib.main")
<module 'lib.main' from '/some/path/lib/main.py'>
>>> lib.main.sayyay()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'lib' is not defined
我确实阅读了 importlib 文档以及此处关于 SO 的几个答案,例如 How to import a module in Python with importlib.import_module and Dynamically import a method in a file, from a string
但是我错过了什么?
import_module
returns 导入的模块。
因此,你需要给导入的模块起一个名字,就像lib.main
>>> lib_main = importlib.import_module("lib.main")
>>> lib_main.sayyay()