从字符串中动态地导入文件中的方法 [英] Dynamically import a method in a file, from a string
本文介绍了从字符串中动态地导入文件中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,说: 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屋!
查看全文