OGeek|极客世界-中国程序员成长平台

标题: python - import module from string variable [打印本页]

作者: 菜鸟教程小白    时间: 2022-4-23 12:56
标题: python - import module from string variable

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

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)

And here is 3 way comparison of above lists through pprint:

enter image description here

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.



Best Answer-推荐答案


The __import__ function can be a bit hard to understand.

If you change

i = __import__('matplotlib.text')

to

i = __import__('matplotlib.text', fromlist=[''])

then i will refer to matplotlib.text.

In Python 2.7 and Python 3.1 or later, you can use importlib:

import importlib

i = importlib.import_module("matplotlib.text")

Some notes






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://www.ogeek.cn/) Powered by Discuz! X3.4