使用Python脚本中的命令创建原始输入

使用Python脚本中的命令创建原始输入,第1张

使用Python脚本中的命令创建原始输入

听起来命令行界面就是您要询问的那部分。将用户输入映射到命令的一种好方法是使用字典,并且在python中,您可以通过在函数名称后加上()来运行对函数的引用。这是一个简单的例子,向您展示我的意思

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


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5632463.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存