经过一番搜索,我找到了两个符合我的需求的库!
第一个是 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)