在Python,所以能够dynamically import an entire module using importlib.import_module(name)
,它返回指定的封装或模块(例如pkg.mod
)。但是,有没有类似的方式来动态导入特定的功能/类/等。从给定的模块以与使用例如from foo import bar
, where the symbol bar
of the module foo
is imported into the symbol table of the importing module?动态等效
例如,如果我尝试导入直接使用importlib.import_module(symbol_name)
的象征,我只是得到一个ImportError:
import importlib
# Importing an entire module works fine
imported_module = importlib.import_module("os.path")
# This doesn't work
imported_symbol = importlib.import_module("os.path.basename")
执行上面的代码打印以下堆栈跟踪:
Traceback (most recent call last):
File "/home/stackoverflow/dev/importtest.py", line 6, in <module>
symbol = importlib.import_module("basename", "os.path.basename")
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'basename'
'itertools'没有'import_module()'。你提到的链接包含'importlib.import_module'。 – ettanany
谢谢;我修正了错字。不知道我是如何管理那个... – errantlinguist