Dan*_*eng 6 python terminal command-line-interface
我想创建一个带有项目选择界面的Python CLI,允许用户从列表中选择一个项目.就像是:
Select a fruit (up/down to select and enter to confirm):
[x] Apple
[ ] Banana
[ ] Orange
Run Code Online (Sandbox Code Playgroud)
我希望用户能够使用向上/向下箭头更改其选择,然后按Enter
确认.
是否存在具有此功能的Python模块?我试着搜索但找不到我想要的东西.
在选择壳Node.js的包不正是我想要的.
该挑Python模块我想要做什么,但它使用的诅咒,并打开了一个简单的GUI.我想避免创建GUI并将所有输出保留在终端中:这可能需要更新显示给终端的行.
我目前正在使用点击,但我不相信它支持此功能.我不确定如何使用cmd
/ 输入这种功能,readline
并且会欣赏任何见解.
Dan*_*eng 14
经过一番搜索,我找到了两个满足我需求的库!
第一个是python-inquirer,一个Inquirer.js的Python端口,一个像Yeoman这样的项目使用的CLI库.我发现这个库有一个非常好的API(建立在祝福之上)但在设计/功能方面缺乏润色.
第二(我将使用)是whaaaaat,问询的另一个Python端口.这个库提供的功能更接近原始的Inquirer.js,正是我所需要的.但是,API不如python-inquirer那么干净.
例子:
python-inquirer
例:
import os
import sys
import re
sys.path.append(os.path.realpath('.'))
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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
对于简单的选择,您可以使用simpleterm-menu包。它简单、小并且不依赖于其他包。
例子:
from simple_term_menu import TerminalMenu
terminal_menu = TerminalMenu(["entry 1", "entry 2", "entry 3"])
choice_index = terminal_menu.show()
Run Code Online (Sandbox Code Playgroud)