从Python的dir()调用模块
简短的问题
从python的dir()函数获取的模块,可以被调用吗?
背景
我正在创建一个自定义的测试运行器,想根据字符串过滤器来选择要运行的模块。下面是我理想的用法示例。
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!
2 个回答
5
当然可以:
import module_a
list_from_a = dir(module_a)
for mod in list_from_a:
if(mod.startswith('mykey_'):
f = getattr(module_a, mod)
f()
7
getattr(module_a, mod)()
getattr是一个内置函数,它需要两个东西:一个对象和一个字符串。它的作用是返回这个对象的某个属性。