简体   繁体   中英

Calling modules from Python dir()

Short Question
Is it possible to call a module as retrieved from the python dir() function?

Background
I am working on building a custom test runner and would like be able to choose which modules to run based on a string filter. See my examples below for ideal usage.

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

Output

Doing something!
Doing something else!
getattr(module_a, mod)()

getattr是一个内置函数,它接受对象和字符串,并返回属性。

Sure:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM