문제
내가 만든 모듈을 동적으로로드하려고합니다.
지금은 제대로 작동합니다.
import structures.index
그러나 동적으로 가져 와서 같은 것을 시도하면 실패합니다.
struct = __import__("structures.index")
제공된 오류는 다음과 같습니다.
Error ('No module named structures.index',)
왜 아이디어가 있습니까?
편집 : 전체 범위를 사용할 때 (일종의 작동합니까?) :
struct = __import__("neoform.structures.index")
오류가 발생하지는 않지만 인덱스 모듈을로드하지 않고 대신 "Neoform"모듈을로드합니다.
"구조"의 결과는 다음과 같습니다.
<module 'neoform' from '/neoform/__init__.py'>
또한 부수적 인 질문으로 동적으로로드 된 모듈 내에서 클래스를 어떻게 인스턴스화 할 수 있습니까? (모든 모듈에 공통 클래스 이름이 포함되어 있다고 가정합니다).
편집 : 솔루션 : (Coonj & Rick에게 감사합니다) 이것은 결국 효과가있었습니다. 왜 (아직) 왜 fromlist
문자를 "A"를 값으로 넣을 때 효과가 있었기 때문에 "분명히 어떤 것도 분명히 사용 되었기 때문에 (파일에 1 개의 클래스 만 있었다는 점을 감안할 때).
def get_struct_module(self, name):
try:
return = __import__("neoform.structures." + name, fromlist='*')
except ImportError, e:
self.out.add("Could not load struct: neoform.structure." + name + "\n\n" + "Error " + str(e.args))
해결책
"실패"가 무엇을 의미하는지 잘 모르겠습니다. __import__('structures.index')
실제로 작동해야하지만 현재 범위에 모듈 이름을 할당하지 않습니다. 이를 수행하려면 (동적으로 가져온 모듈에서 클래스를 사용하려면) 사용해야합니다.
structures = __import__('structures.index')
structures.index.SomeClass(...)
완전한 세부 사항 __import__
사용 가능합니다 여기.
편집 : (질문 편집 기반)
가져 오기 위해 neoform.structures.index
, 그리고 반환 index
모듈, 당신은 다음을 수행합니다.
structures = __import__('neoform.structures.index',
fromlist=['does not in fact matter what goes here!'])
따라서 패키지 이름 목록이있는 경우 packages
, 당신은 그들의 가져올 수 있습니다 index
모듈과 일부를 인스턴스화합니다 MyClass
다음 코드를 사용하는 각각의 클래스 :
modules = [ __import__('neoform.%s.index' % pkg, fromlist=['a'])
for pkg in packages ]
objects = [ m.MyClass() for m in modules ]
다른 팁
하위 모듈을 가져 오려면 fromlist
arg __import__()
FO 예제, 동등한 :
import structures.index
이다:
structures = __import__('structures', fromlist=['index'])
지도에서 이것을하는 것은 조금 더 까다 롭습니다 ...
import mod1.index
import mod2.index
import mod3.index
이러한 수입의 경우 새로운 기능을 정의하여 index
각 모듈의 하위 모듈 :
def getIndexMods(mod_names):
mod_list = map(lambda x: __import__(x, fromlist='index'))
index_mods = [mod.index for mod in mod_list]
return index_mods
이제 모든 인덱스 모듈에 대한 참조를 얻기 위해이 작업을 수행 할 수 있습니다.
index_mods = getIndexMods(['mod1', 'mod2', 'mod3'])
또한 '인덱스'라는 이름이 아닌 하위 모듈을 잡으려면 다음을 수행 할 수 있습니다.
mod1, mod2, mod3 = map(lambda x,y: __import__(x, fromlist=y),
['mod1', 'mod2', 'mod3'], ['index1', 'index2', 'index3'])
이 헬퍼 방법과 함께 전체 범위 ( "neoform.structures.index")를 사용하십시오.
def import_module(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
module = import_module("neoform.structures.index")
# do stuff with module
여기에 Java 프로그래머이지만 필요하다고 생각합니다. IMP 모듈
>>> import imp
>>> fm = imp.find_module('index', ['./structures']) # for submodule
>>> mymod = imp.load_module('structures.index', *fm)
>>> mymod
<module 'structures.index' from './structures/index.pyc'>
>>> x = mymod.insideIndex()
Initialising index class...
짜잔!
왜 지구상에서 교체 할 것인가
import structures.index
~와 함께
map(__import__, ["structures.index"])
첫 번째 (a) 작동, (b) ~이다 동적 및 (c)는 직접 지원됩니다. 선택하기 쉬운 일반 텍스트 소스를 더 복잡한 것으로 바꾸는 데 가능한 사용 사례는 무엇입니까?
간단히 말해서 :하지 마십시오. 가치가 없습니다.
편집하다
"데이터베이스에서 가져 오기"는 고귀한 노력이지만 여전히 합리적이지 않습니다. 수입에 의존하는 코드 블록은 무엇입니까? 전체 코드 블록 (가져 오기 등)은 실행하려는 것입니다. 가져 오기, 진술 및 모든 것의 전체 코드 블록은 평범한 오래된 Python 모듈 파일이어야합니다.
파일 시스템에서 해당 코드 블록을 가져옵니다. 데이터베이스를 사용하여 파일의 저자 인 파일 (데이터베이스를 사용하려는 내용)을 식별하십시오. 그러나 단순히 모듈을 가장 간단한 방법으로 가져오고 실행하십시오.
정말 늦은 게시물. 그러나 나는 Google 에서이 질문을 찾고 있었다. 나는 시행 착오를했다. 이 스 니펫이 도움이 될지 확실하지 않지만 여기에 있습니다. 플라스크 사이트에 사용합니다.
modules = ['frontend', 'admin']
for module in modules:
mod = __init__('controllers.%s' % module, fromlist=[module])
app.register_blueprint(mod.blueprint_mod)
# or
from importlib import import_module
modules = ['frontend', 'admin']
for module in modules:
mod = import_module('controllers.%s' % module)
app.regitster_blueprint(mod.blueprint_mod)