문자열 변수에서 모듈 가져 오기
관심있는 서브 모듈 패키지가 제공하는 MPL 자체 라이브러리와는 다른 MPL (nested matplotlib) 라이브러리에 대한 문서 (개인용)를 작성하고 있습니다. 향후 MPL 릴리스에서 문서 생성을 자동화 할 Python 스크립트를 작성 중입니다.
관심있는 서브 모듈 / 패키지를 선택하고 목록을 생성하고 처리 할 기본 클래스를 나열하려고합니다.pydoc
문제는 파이썬이 문자열에서 하위 모듈을로드하도록 지시하는 방법을 찾을 수 없다는 것입니다. 내가 시도한 것의 예는 다음과 같습니다.
import matplotlib.text as text
x = dir(text)
.
i = __import__('matplotlib.text')
y = dir(i)
.
j = __import__('matplotlib')
z = dir(j)
다음은 pprint를 통해 위 목록을 3 가지 방법으로 비교 한 것입니다.
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.
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
If you're trying to import something from a sub-folder e.g.
./feature/email.py
, the code will look likeimportlib.import_module("feature.email")
You can't import anything if there is no
__init__.py
in the folder with file you are trying to import
importlib.import_module
is what you are looking for. It returns the imported module. (Only available for Python >= 2.7 or 3.x):
import importlib
mymodule = importlib.import_module('matplotlib.text')
You can thereafter access anything in the module as mymodule.myclass
, etc.
spent some time trying to import modules from a list, and this is the thread that got me most of the way there - but I didnt grasp the use of ___import____ -
so here's how to import a module from a string, and get the same behavior as just import. And try/except the error case, too. :)
pipmodules = ['pycurl', 'ansible', 'bad_module_no_beer']
for module in pipmodules:
try:
# because we want to import using a variable, do it this way
module_obj = __import__(module)
# create a global object containging our module
globals()[module] = module_obj
except ImportError:
sys.stderr.write("ERROR: missing python module: " + module + "\n")
sys.exit(1)
and yes, for python 2.7> you have other options - but for 2.6<, this works.
I developed these 3 useful functions:
def loadModule(moduleName):
module = None
try:
import sys
del sys.modules[moduleName]
except BaseException as err:
pass
try:
import importlib
module = importlib.import_module(moduleName)
except BaseException as err:
serr = str(err)
print("Error to load the module '" + moduleName + "': " + serr)
return module
def reloadModule(moduleName):
module = loadModule(moduleName)
moduleName, modulePath = str(module).replace("' from '", "||").replace("<module '", '').replace("'>", '').split("||")
if (modulePath.endswith(".pyc")):
import os
os.remove(modulePath)
module = loadModule(moduleName)
return module
def getInstance(moduleName, param1, param2, param3):
module = reloadModule(moduleName)
instance = eval("module." + moduleName + "(param1, param2, param3)")
return instance
And everytime I want to reload a new instance I just have to call getInstance() like this:
myInstance = getInstance("MyModule", myParam1, myParam2, myParam3)
Finally I can call all the functions inside the new Instance:
myInstance.aFunction()
The only specificity here is to customize the params list (param1, param2, param3) of your instance.
참고 URL : https://stackoverflow.com/questions/8718885/import-module-from-string-variable
'programing tip' 카테고리의 다른 글
Chrome 확장 프로그램에서 현재 탭의 URL을 얻으려면 어떻게해야하나요? (0) | 2020.05.31 |
---|---|
기본 그래픽에서 플로팅 영역 외부에 범례를 플롯 하시겠습니까? (0) | 2020.05.31 |
sp_executesql 결과를 변수로 얻는 방법은 무엇입니까? (0) | 2020.05.31 |
C # short / long / int 리터럴 형식? (0) | 2020.05.31 |
여백 상단이 범위 요소에서 작동하지 않습니까? (0) | 2020.05.31 |