Python:通过用户输入从字典中调用函数

时间:2014-04-05 07:11:16

标签: python

我正在尝试使用字典键调用函数。目前字典中只有一个功能,但我计划添加更多功能。下面的代码用于显示列表,因为函数'loadlist'没有参数,我在打开文件时将'gameone.txt'写入正文代码中。

我希望将文件名作为loadlist函数的参数,以便用户输入例如... loadlist('gameone.txt')或loadlist('gametwo.txt')等取决于他们想要什么显示。

def interact():

command = raw_input('Command:')

def loadlist():

    with open('gameone.txt', 'r') as f:
        for line in f:
            print line


dict = {'loadlist': loadlist}
dict.get(command)()

return interact()

相互作用()

我已经尝试了下面的代码,但我无法解决我的问题。

def interact():

command = raw_input('Command:')

def loadlist(list):

    with open(list, 'r') as f:
        for line in f:
            print line


dict = {'loadlist': loadlist}
dict.get(command)()

return interact()

相互作用()

感谢您的任何意见。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用* args。

def interact():

    command,file_to_load = raw_input('Command:').split(' ')

    # *args means take the parameters passed in and put them in a list called args
    def loadlist(*args):

        # get the argument from args list
        filename = args[0]

        with open(filename, 'r') as f:
            for line in f:
                print line


    dict = {'loadlist': loadlist}
    dict.get(command)(file_to_load)

interact()