从Python dir()调用模块
发布时间:2021-02-20 20:30:35 所属栏目:Python 来源:互联网
导读:简短的问题 是否可以调用从 python dir()函数检索的模块? 背景 我正在构建一个自定义测试运行器,并希望能够根据字符串过滤器选择要运行的模块.有关理想用法,请参阅下面的示例. module_a.py def not_mykey_dont_do_this(): print I better not do thisdef myk
简短的问题
背景 module_a.py def not_mykey_dont_do_this(): print 'I better not do this' def mykey_do_something(): print 'Doing something!' def mykey_do_somethingelse(): print 'Doing something else!' module_b.py import module_a list_from_a = dir(module_a) # ['not_mykey_dont_do_this','mykey_do_something','mykey_do_somethingelse'] for mod in list_from_a: if(mod.startswith('mykey_'): # Run the module module_a.mod() # Note that this will *not* work because 'mod' is a string 产量 Doing something! Doing something else! 解决方法getattr(module_a,mod)() getattr是一个内置函数,它接受对象和字符串,并返回属性. (编辑:甘南站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |