prompt_toolkit 是一个用于构建 CLI 应用程序的 Python 库,可以让我们轻松地构建强大的交互式命令行应用程序。
除此之外,prompt_toolkit 还支持 ANSI 转义序列,可以在控制台中创建彩色的文本和界面元素。prompt_toolkit 还可以通过支持异步输入和输出,使得处理 I/O 密集型任务变得更加高效。
from prompt_toolkit import prompt
while 1:
user_input = prompt('>')
print(user_input)
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
while 1:
user_input = prompt('>',
history=FileHistory('history.txt'),
)
print(user_input)
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
while 1:
user_input = prompt('>',
history=FileHistory('history.txt'),
auto_suggest=AutoSuggestFromHistory(),
)
print(user_input)
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.contrib.completers import WordCompleter
SQLCompleter = WordCompleter(['select', 'from', 'insert', 'update', 'delete', 'drop'],
ignore_case=True)
while 1:
user_input = prompt('SQL>',
history=FileHistory('history.txt'),
auto_suggest=AutoSuggestFromHistory(),
completer=SQLCompleter,
)
print(user_input)
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.contrib.completers import WordCompleter
SQLCompleter = WordCompleter(['select', 'from', 'insert', 'update', 'delete', 'drop'],
ignore_case=True)
while 1:
user_input = prompt('SQL>',
history=FileHistory('history.txt'),
auto_suggest=AutoSuggestFromHistory(),
completer=SQLCompleter,
multiline=True,
)
print(user_input)
Pygments 是一个提供语法高亮的库,内建支持超过 300 种语言。
from pygments.lexers.python import PythonLexer # Python 词法分析器
from pygments.style import Style as PygmentsStyle # 颜料词法分析器
from pygments.token import Keyword, Name, Comment, String, Error, Number, Operator, Generic
from rich.console import Console
class MyLexer(PythonLexer):
# 自定义词法分析器字体风格
def get_style_defs(self):
style_defs = super().get_style_defs()
style_defs += "\n" + PygmentsStyle.from_dict({
Keyword: '#ff79c6 bold', # 关键字
Name.Function: '#bd93f9 bold underline', # 函数名
Name.Class: '#bd93f9 bold', # 类名
Name.Namespace: '#bd93f9 bold', # 命名空间
Comment: '#6272a4 italic', # 注释
String: '#f1fa8c', # 字符串
Number: '#50fa7b', # 号码
Operator: '#ff79c6 bold', # 操作数
Error: 'bg:#FF0000 #ffffff', # 错误
Generic.Heading: '#bd93f9 bold', # 常规
Generic.Subheading: '#bd93f9 bold underline',
Generic.Emph: 'italic',
Generic.Strong: 'bold',
Generic.Prompt: 'bold',
}).as_pygments()
return style_defs
lexer = PygmentsLexer(MyLexer) # 颜料词法分析器
style = Style.from_dict({ # 定义样式
"prompt": "bold #50fa7b",
"input": "#f8f8f2",
"output": "#f8f8f2",
"highlighted": "bg:#44475a #f8f8f2",
"separator": "#6272a4",
"error": "#ff5555 bold",
"info": "#8be9fd",
})
session = PromptSession(history=history, completer=completer, auto_suggest=auto_suggest, lexer=lexer, style=style)