나는 문자열이 있습니다 abc.def.ghi.jkl.myfile.mymethod
. 동적으로 가져 오려면 어떻게합니까 mymethod
?
내가 어떻게했는지는 다음과 같습니다.
def get_method_from_file(full_path):
if len(full_path) == 1:
return map(__import__,[full_path[0]])[0]
return getattr(get_method_from_file(full_path[:-1]),full_path[-1])
if __name__=='__main__':
print get_method_from_file('abc.def.ghi.jkl.myfile.mymethod'.split('.'))
개별 모듈 가져 오기가 전혀 필요한지 궁금합니다.
편집 : Python 버전 2.6.5를 사용하고 있습니다.
답변
Python 2.7에서는 importlib.import_module () 함수를 사용할 수 있습니다 . 다음 코드를 사용하여 모듈을 가져오고 그 안에 정의 된 객체에 액세스 할 수 있습니다.
from importlib import import_module
p, m = name.rsplit('.', 1)
mod = import_module(p)
met = getattr(mod, m)
met()
답변
개별 모듈을 가져올 필요가 없습니다. 이름을 가져 오려는 모듈을 가져오고 fromlist
인수를 제공하면 충분합니다 .
def import_from(module, name):
module = __import__(module, fromlist=[name])
return getattr(module, name)
예를 abc.def.ghi.jkl.myfile.mymethod
들어이 함수를 다음과 같이 호출하십시오.
import_from("abc.def.ghi.jkl.myfile", "mymethod")
(모듈 수준 함수는 메서드가 아니라 Python에서 함수라고합니다.)
이러한 간단한 작업의 경우 importlib
모듈 을 사용하는 데 이점이 없습니다 .
답변
Python <2.7의 경우 내장 메서드 __ import__를 사용할 수 있습니다.
__import__('abc.def.ghi.jkl.myfile.mymethod', fromlist=[''])
Python> = 2.7 또는 3.1의 경우 편리한 메소드 importlib.import_module 이 추가되었습니다. 다음과 같이 모듈을 가져옵니다.
importlib.import_module('abc.def.ghi.jkl.myfile.mymethod')
업데이트 : 주석에 따라 업데이트 된 버전 ( 끝까지 가져올 문자열을 읽지 않았고 모듈 자체가 아니라 모듈의 메서드를 가져와야한다는 사실을 놓 쳤음을 인정해야합니다) :
Python <2.7 :
mymethod = getattr(__import__("abc.def.ghi.jkl.myfile", fromlist=["mymethod"]))
Python> = 2.7 :
mymethod = getattr(importlib.import_module("abc.def.ghi.jkl.myfile"), "mymethod")
답변
로컬 네임 스페이스에 대해 수행하려는 작업이 명확하지 않습니다. 나는 당신이 my_method
로컬로 원한다고 가정합니다 output = my_method()
.
# This is equivalent to "from a.b.myfile import my_method"
the_module = importlib.import_module("a.b.myfile")
same_module = __import__("a.b.myfile")
# import_module() and __input__() only return modules
my_method = getattr(the_module, "my_method")
# or, more concisely,
my_method = getattr(__import__("a.b.myfile"), "my_method")
output = my_method()
my_method
로컬 네임 스페이스 에만 추가하는 동안 모듈 체인을로드합니다. sys.modules
가져 오기 전과 후의 키를보고 변경 사항을 볼 수 있습니다 . 다른 답변보다 명확하고 정확하기를 바랍니다.
완전성을 위해 전체 체인을 추가하는 방법입니다.
# This is equivalent to "import a.b.myfile"
a = __import__("a.b.myfile")
also_a = importlib.import_module("a.b.myfile")
output = a.b.myfile.my_method()
# This is equivalent to "from a.b import myfile"
myfile = __import__("a.b.myfile", fromlist="a.b")
also_myfile = importlib.import_module("a.b.myfile", "a.b")
output = myfile.my_method()
마지막으로 __import__()
프로그램 시작 후 검색 경로를 사용 하고 수정 한 경우 __import__(normal args, globals=globals(), locals=locals())
. 그 이유는 복잡한 논의입니다.
답변
from importlib import import_module
name = "file.py".strip('.py')
# if Path like : "path/python/file.py"
# use name.replaces("/",".")
imp = import_module(name)
# get Class From File.py
model = getattr(imp, "classNameImportFromFile")
NClass = model() # Class From file
답변
이 웹 사이트에는 좋은 해결책이 있습니다 : load_class . 다음과 같이 사용합니다.
foo = load_class(package.subpackage.FooClass)()
type(foo) # returns FooClass
요청한대로 웹 링크의 코드는 다음과 같습니다.
import importlib
def load_class(full_class_string):
"""
dynamically load a class from a string
"""
class_data = full_class_string.split(".")
module_path = ".".join(class_data[:-1])
class_str = class_data[-1]
module = importlib.import_module(module_path)
# Finally, we retrieve the Class
return getattr(module, class_str)