从字符串动态导入文件中的方法 [英] Dynamically import a method in a file, from a string

查看:13
本文介绍了从字符串动态导入文件中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,比如:abc.def.ghi.jkl.myfile.mymethod.如何动态导入mymethod?

I have a string, say: abc.def.ghi.jkl.myfile.mymethod. How do I dynamically import 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('.'))

我想知道是否需要导入单个模块.

I am wondering if the importing individual modules is required at all.

我使用的是 Python 2.6.5 版.

I am using Python version 2.6.5.

推荐答案

从 Python 2.7 开始,您可以使用 importlib.import_module() 函数.您可以使用以下代码导入模块并访问其中定义的对象:

From Python 2.7 you can use the importlib.import_module() function. You can import a module and access an object defined within it with the following code:

from importlib import import_module

p, m = name.rsplit('.', 1)

mod = import_module(p)
met = getattr(mod, m)

met()

这篇关于从字符串动态导入文件中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆