ChatGPT解决这个技术问题 Extra ChatGPT

从字符串动态导入文件中的方法

我有一个字符串,比如: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 版。


f
frm

从 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()

值得注意的是 Python 文档建议使用 importlib.import_module() 而不是 __import__()docs.python.org/2/library/functions.html#__import__ - 用于 2.7+。
import_module + rsplit = 一条真道。
S
Sven Marnach

您不需要导入各个模块。导入要从中导入名称的模块并提供 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 模块没有任何优势。


import_from() 为我指明了正确的方向。 myClass = getattr(__import__("module.to.import", fromlist=["myClassName"]), "myClassName")。谢谢您的帮助!
__import__ 方法确实有效。但请尝试运行 help(__import__)。它说“因为这个函数是供 Python 解释器使用的,而不是一般用途,最好使用 importlib.import_module() 以编程方式导入模块。”
@twasbrillig:当我回答这个问题时,Python 2.5 和 2.6 仍在广泛使用中。今天,当然最好改用 importlib
酷,谢谢。更新答案以反映这一点可能是个好主意。
g
gecco

对于 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')

更新:根据评论更新版本(我必须承认我直到最后都没有阅读要导入的字符串,我错过了应该导入模块的方法而不是模块本身的事实):

蟒蛇 < 2.7 :

mymethod = getattr(__import__("abc.def.ghi.jkl.myfile", fromlist=["mymethod"]))

蟒蛇> = 2.7:

mymethod = getattr(importlib.import_module("abc.def.ghi.jkl.myfile"), "mymethod")

这些解决方案都不起作用,因为第一个参数必须是 __import__()importlib.import_module() 中的 模块名称
importlib.import_module('abc.def.ghi.jkl.myfile.mymethod') 将不起作用,因为您必须指定“以绝对或相对术语导入的模块”而不是方法的“限定”名称。
显然,这不起作用,因为要导入的第一个参数应该是模块,而不是字符串。
C
Cabbage soup
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 

感谢您的回答,只是一个小问题:我认为 .strip() 在您所说的情况下行为不正确。具体来说,如果文件以“py”开头,这些字符也将被删除。例如,"pyfile.py".strip(".py") 生成 "file",在这种情况下最好生成 "pyfile"。不过,name.replace(".py","") 工作得很好。
O
Ondrej Slinták

目前尚不清楚您要对本地命名空间做什么。我假设您只想将 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())。为什么是一个复杂的讨论。


the_modulesame_module 的第一个示例是错误的,会产生不同的结果。投反对票。
t
the-typist

这个网站有一个很好的解决方案: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)

请包括给定链接中的摘要/代码。仅链接的答案不是很好,因为它们容易链接腐烂。
D
Daniel Roseman

使用 importlib(仅限 2.7+)。


我使用 2.6.5。我可以做 from __future__ 件事吗?
不,__future__ 用于语言功能,而不是新的 stdlib 模块。
使用上述示例中的内置 __import__。它可以回溯到 2.5,并且在此之前没有关键字。
K
Kris Hardy

我倾向于这样做的方式(以及许多其他库,例如 pylons 和 paste,如果我没记错的话)是通过在它们之间使用“:”将模块名称与函数/属性名称分开.请参见以下示例:

'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()

为什么要这样做?这需要调用者用冒号连接模块名和属性名,函数需要在冒号处再次拆分。为什么不首先使用两个参数呢?
通常,如果您使用配置文件(.yaml、.ini 等)将回调从框架连接到应用程序,就会出现这种情况。然后,您可以在配置文件中使用单个字符串指定框架应调用的函数等。
好吧,是的,您可能希望选择它作为配置文件语法。但这与OP的问题有什么关系? (即使我选择了它作为我的配置文件语法,我更希望它由我的配置文件解析器解析,而不是由随机 API 函数解析。)
A
Aymen Alsaadi

这个怎么样 :

def import_module(name):

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

不鼓励使用魔法方法。请改用 importlib。
你能详细说明为什么它令人沮丧吗? @dephinera
好吧,因为魔术方法旨在由解释器调用,而不是由我们的代码显式调用。通过显式调用它们,我们相信它们的签名永远不会改变,但它可能会在未来的语言版本中改变。
@dephinera,我以前没有看到类似的东西。可以参考一下链接吗。我用谷歌搜索,找不到任何东西。