您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

使用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 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()
python 2022/1/1 18:38:37 有244人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶