如何使用用户输入迭代模块

时间:2014-02-24 13:10:31

标签: python function python-3.x getattr

用户输入模块,如图所示迭代导入的模块。我怎么能让它迭代所有导入的模块,因为它只迭代foo

from packageA import foo # has open_book() function
from packageB import bar# has read_music() function
from packageC import loader# has loader() function
import re
import sys
import difflib

def search():
    name = input('Please enter your query: ').lower().split()

    while True:    
        for name in ["open_book","read_music","loader"  ]:  #help code here          
            getattr(foo, "open_book")()
            getattr(bar, "read_music")()
    else:        
        print ('Try again')

1 个答案:

答案 0 :(得分:1)

如果您想让用户输入可能在这3个模块上可用的任何功能名称,请将所有3个模块存储在列表或元组中并循环显示,然后测试该功能是否可用:

modules = (foo, bar, loader)

def search():
    name = input('Please enter your query: ').lower()

    for module in modules:
        function = getattr(module, name, None)
        if function is not None:
            function()
            break

    else:        
        print ('Try again')