You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何根据用户输入调用存储在字典中的对应函数

你已经完成了核心的指令-函数映射字典的定义,只需要在判断指令存在后,取出字典对应的函数对象加()执行即可。

完整可运行的修改后代码

def userInput():
    RUN = 1
    while RUN != 0:
        USER = input('↪ ').lower()
        if USER in cmd:
            # 核心执行逻辑:取出函数对象后调用
            cmd[USER]()
        else:
            # 可选补充:未知指令提示
            print("无效指令,输入help查看可用指令")

def helpCmd():
    print('THIS IS THE HELP MENU AHAHAHA !')

def connexion():
    print("› SSH\n› FTP\n")

cmd = {
   'help': helpCmd,
   'connexion': connexion
}

# 启动程序入口
if __name__ == "__main__":
    userInput()

核心逻辑说明

  • 你在cmd字典中存储的是函数本身的引用,没有加()时不会执行函数,只会拿到函数对象
  • 确认指令存在后,用cmd[USER]拿到对应函数,末尾加()即可触发函数执行

扩展支持带参数的指令

如果后续需要支持带参数的指令(比如输入connect 192.168.1.100传入目标IP),可以按如下方式修改:

# 带参数的函数示例
def connect(ip):
    print(f"正在尝试连接到 {ip}")

cmd = {
    'help': helpCmd,
    'connexion': connexion,
    'connect': connect
}

def userInput():
    RUN = 1
    while RUN != 0:
        input_content = input('↪ ').lower().split()
        if not input_content:
            continue
        cmd_name = input_content[0]
        cmd_args = input_content[1:]
        if cmd_name in cmd:
            # 用*解包参数传入函数
            cmd[cmd_name](*cmd_args)
        else:
            print("无效指令,输入help查看可用指令")

内容的提问来源于stack exchange,提问作者Pierre Loti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:18:03