使用select接口创建Python命令行界面

42

我想创建一个Python CLI,并带有选择项界面,允许用户从列表中选择一个项目。类似于:

Select a fruit (up/down to select and enter to confirm):
[x] Apple
[ ] Banana
[ ] Orange

我希望用户可以使用上下箭头更改选择,并按Enter键确认。

是否存在具有此功能的Python模块? 我尝试搜索,但没有找到完全符合我的要求的。

select-shell Node.js 包 正好符合我的需求。

pick Python 模块 可以实现我想要的功能,但它使用curses并打开一个简单的GUI。 我想避免创建GUI并将所有输出保留在终端:这可能需要更新显示在终端的行。

我目前正在使用click,但我不认为它支持此功能。 我不确定如何使用cmd/readline实现这种特性,并感谢任何见解。

4个回答

57

经过一番搜索,我找到了两个符合我的需求的库!

第一个是 python-inquirer,它是Inquirer.js的 Python 移植版本,Inquirer.js 是 Yeoman 等项目中使用的 CLI 库。我发现这个库有着非常好的 API(建立在 blessings 之上),但在设计和功能方面缺乏完善。

第二个(我将使用它)是 whaaaaat,另一个 Inquirer 的 Python 移植版本。这个库的功能更接近原始的 Inquirer.js,正是我所需要的。然而,其 API 没有 python-inquirer 那样干净简洁。

示例:

python-inquirer 示例:

from pprint import pprint
import inquirer

questions = [
    inquirer.List(
        "size",
        message="What size do you need?",
        choices=["Jumbo", "Large", "Standard", "Medium", "Small", "Micro"],
    ),
]

answers = inquirer.prompt(questions)
pprint(answers)

whaaaaat例子:

from whaaaaat import prompt, print_json, Separator

questions = [
    {
        "type": "list",
        "name": "theme",
        "message": "What do you want to do?",
        "choices": [
            "Order a pizza",
            "Make a reservation",
            Separator(),
            "Ask for opening hours",
            {"name": "Contact support", "disabled": "Unavailable at this time"},
            "Talk to the receptionist",
        ],
    },
    {
        "type": "list",
        "name": "size",
        "message": "What size do you need?",
        "choices": ["Jumbo", "Large", "Standard", "Medium", "Small", "Micro"],
        "filter": lambda val: val.lower(),
    },
]

answers = prompt(questions)
print_json(answers)

6
注意:(1)Python-inquirer的Windows支持是实验性的。 (2)Whaaaat已经过时,开发者在自述文件中表示他没有时间继续开发该项目。 - miwe
我认为python-inquirer也使用了curses? - wong2

8

对于简单的选择,您可以使用simple-term-menu软件包。它简单、小巧,没有依赖其他软件包。

例子:

from simple_term_menu import TerminalMenu

terminal_menu = TerminalMenu(["entry 1", "entry 2", "entry 3"])
choice_index = terminal_menu.show()

simple-term-menu


10
注意:simple_term_menu 在 Windows 上无法使用。请参阅 https://github.com/IngoMeyer441/simple-term-menu#overview。 - miwe

8

3
+1 让我从“找一个与Windows兼容的选项会很麻烦”变成了“哦...应该选择哪一个呢?” - Paiusco

0

你提到了click package,并提到你不确定如何实现这个功能。似乎choice-options是实现单选题的预期方式。

生成的输出结果可能不会像其他答案中提到的一些包那样好看。然而,click很好维护,活跃,并且可以在UNIX和WIN上运行 - 如果你计划发布一个库,这是至关重要的因素。


1
单选可能会成为OP的决定因素,它与交互式多选界面有着明显不同的用户体验。 - verwirrt
真的:我对选择选项不太熟悉,但是是的,看起来好像不支持多选题。然而,我理解 OP 的问题("选择一种水果")是明确针对单选题的...... - miwe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接