programing

문자열에서 파일의 메서드를 동적으로 가져옵니다.

cafebook 2023. 10. 25. 23:43
반응형

문자열에서 파일의 메서드를 동적으로 가져옵니다.

끈이 있어요, 뭐라고요?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")

(Module-level 함수는 메서드가 아닌 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")
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 

로컬 네임스페이스에 대해 수행하려는 작업이 불분명합니다.당신이 원하는 건 그저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()) 그 이유는 복잡한 논의입니다.

이 웹사이트에는 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)

(2.7+만)을 사용합니다.

파일론 및 붙여넣기와 같은 여러 다른 라이브러리(메모리가 올바르게 작동하는 경우)와 모듈 이름을 함수/속성 이름에서 ':'로 구분하는 것이 제가 이 작업을 수행하는 방법입니다.다음 예를 참조하십시오.

'abc.def.ghi.jkl.myfile:mymethod'

이렇게 하면.import_from(path)기능이 좀 더 쉽게 사용할 수 있습니다.

def import_from(path):
    """
    Import an attribute, function or class from a module.
    :attr path: A path descriptor in the form of 'pkg.module.submodule:attribute'
    :type path: str
    """
    path_parts = path.split(':')
    if len(path_parts) < 2:
        raise ImportError("path must be in the form of pkg.module.submodule:attribute")
    module = __import__(path_parts[0], fromlist=path_parts[1])
    return getattr(module, path_parts[1])


if __name__=='__main__':
    func = import_from('a.b.c.d.myfile:mymethod')
    func()

이거 어때:

def import_module(name):

    mod = __import__(name)
    for s in name.split('.')[1:]:
        mod = getattr(mod, s)
    return mod

언급URL : https://stackoverflow.com/questions/8790003/dynamically-import-a-method-in-a-file-from-a-string

반응형