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

如何用Python inquirer实现带选项的自由输入式提问?

实现混合选择与自由输入的提问方案

基于现有inquirer库的实现方法

无需更换库,可通过两种思路实现需求:

方案一:拆分交互流程

结合List和Text类型,先让用户在预设选项与「自定义输入」中选择,再根据选择结果处理:

import inquirer

# 预设选项+自定义入口
choices = ["1", "2", "3", "自定义输入"]
select_question = [
    inquirer.List('selected',
                  message="请选择或选择自定义输入",
                  choices=choices,
                  )
]
select_result = inquirer.prompt(select_question)

# 根据选择结果获取最终输入
if select_result['selected'] == "自定义输入":
    custom_question = [inquirer.Text('content', message="请输入自定义内容")]
    final_answer = inquirer.prompt(custom_question)['content']
else:
    final_answer = select_result['selected']

print(f"最终输入内容:{final_answer}")

方案二:自定义List组件(进阶)

通过继承inquirer的List类,重写键盘事件监听逻辑,允许用户输入非预设选项的内容。这种方式需要对inquirer的底层交互逻辑有一定了解,实现复杂度较高,但能做到更贴近需求的交互体验。

替代库方案

如果觉得上述方法不够简洁,可使用questionary库,它原生支持混合选择与自由输入的交互类型:

import questionary

answer = questionary.autocomplete(
    "请选择或输入内容:",
    choices=["1", "2", "3"],
    validate=lambda _: True  # 允许任意输入内容
).ask()

print(f"最终输入内容:{answer}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:56:05