Create a raw input with commands inside a Python script

。_饼干妹妹 提交于 2019-11-29 18:20:50

It sounds like the command line interface is that part that you are asking about. One good way to map user inputs to commands is to use a dictionary and the fact that in python you can run a reference to a function by putting () after it's names. Here's a quick example showing you what I mean

def firstThing():  # this could be your 'cd' task
    print 'ran first task'

def secondThing(): # another task you would want to run
    print 'ran second task'

def showCommands(): # a task to show available commands
    print functionDict.keys()

# a dictionary mapping commands to functions (you could do the same with classes)
functionDict = {'f1': firstThing, 'f2': secondThing, 'help': showCommands}

# the actual function that gets the input
def main():
    cont = True
    while(cont):
        selection = raw_input('enter your selection ')
        if selection == 'q': # quick and dirty way to give the user a way out
            cont = False
        elif selection in functionDict.keys():
            functionDict[selection]()
        else:
            print 'my friend, you do not know me. enter help to see VALID commands'

if __name__ == '__main__':
    main()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!