从字符串变量导入模块 [英] import module from string variable
问题描述
我正在编写有关matplotlib(MPL)嵌套库的文档(个人),该文档与感兴趣的子模块软件包所提供的MPL有所不同.我正在编写Python脚本,希望该脚本可以自动从将来的MPL版本中生成文档.
我选择了感兴趣的子模块/程序包,并希望列出其主要类,然后从中生成列表并使用pydoc
I'm working on a documentation (personal) for nested matplotlib (MPL) library, which differs from MPL own provided, by interested submodule packages. I'm writing Python script which I hope will automate document generation from future MPL releases.
I selected interested submodules/packages and want to list their main classes from which I'll generate list and process it with pydoc
问题是我找不到指示Python从字符串加载子模块的方法.这是我尝试过的示例:
Problem is that I can't find a way to instruct Python to load submodule from string. Here is example of what I tried:
import matplotlib.text as text
x = dir(text)
.
i = __import__('matplotlib.text')
y = dir(i)
.
j = __import__('matplotlib')
z = dir(j)
这是通过pprint比较上述列表的三种方式:
And here is 3 way comparison of above lists through pprint:
我不理解y
对象中加载了什么-它是基础matplotlib
以及其他内容,但是它缺少我想要的信息,而这是matplotlib.text
包中的主要类.它是屏幕截图(x
列表)中最上面的蓝色部分
I don't understand what's loaded in y
object - it's base matplotlib
plus something else, but it lack information that I wanted and that is main classes from matplotlib.text
package. It's top blue coloured part on screenshot (x
list)
请不要建议将狮身人面像作为另一种方法.
Please don't suggest Sphinx as different approach.
推荐答案
__import__
函数可能有点难以理解.
The __import__
function can be a bit hard to understand.
如果您更改
i = __import__('matplotlib.text')
到
i = __import__('matplotlib.text', fromlist=[''])
然后i
指的是matplotlib.text
.
在Python 2.7和Python 3.1或更高版本中,您可以使用importlib
:
In Python 2.7 and Python 3.1 or later, you can use importlib
:
import importlib
i = importlib.import_module("matplotlib.text")
一些笔记
-
如果您尝试从子文件夹中导入某些内容,例如
./feature/email.py
,代码将类似于importlib.import_module("feature.email")
如果包含要导入文件的文件夹中没有__init__.py
,则无法导入任何内容
You can't import anything if there is no __init__.py
in the folder with file you are trying to import
这篇关于从字符串变量导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!