我想创建一个带有项目选择界面的 Python CLI,允许用户从列表中选择一个项目。像这样的东西:
Select a fruit (up/down to select and enter to confirm):
[x] Apple
[ ] Banana
[ ] Orange
我希望用户能够使用向上/向下箭头更改他们的选择,然后按 Enter
确认。
是否存在具有此功能的 Python 模块?我尝试搜索但找不到我想要的内容。
select-shell Node.js package完全按照我的意愿行事。
pick Python module做我想做的,但它使用 curses 并打开一个简单的 GUI。我想避免创建 GUI 并将所有输出保留在终端中:这可能需要更新显示在终端上的行。
我目前正在使用 click但我不相信它支持此功能。我不确定如何使用 cmd
/readline
准确地实现这种功能,如果有任何见解,我将不胜感激。
最佳答案
经过一番搜索,我找到了两个满足我需求的库!
第一个是python-inquirer , Inquirer.js 的 Python 端口,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)
关于python - 使用选择界面创建 Python CLI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45022566/