Python 命令行 prompt_toolkit 库详解
prompt_toolkit 是一个用于构建强大交互式命令行的 Python 工具库。接下来通过本文给大家介绍Python 命令行 prompt_toolkit 库的相关知识,感兴趣的朋友一起看看吧
目录
一. 使用 Bash 下常用快捷键
二. 实现查找历史命令
三. 根据历史输入自动提示
四. 实现输入的自动补全
Python 的第三方库 prompt_toolkit
用于打造交互式命令行,在交互式场景的使用中,prompt_toolkit
具有以下特点:
语法高亮
支持多行编辑
支持代码补全
支持自动提示
使用鼠标移动光标
支持查询历史
对 Unicode 支持良好
跨平台
支持 Emacs 与 Vi 风格的快捷键
prompt_toolkit
在使用前需要先进行安装:
pip install prompt_toolkit
一. 使用 Bash 下常用快捷键
想必很多开发者在创建交互式命令行工具时,使用最多的还是 input
和 raw_input
。比如下面的代码读取用户输入数据,并进行打印:
1 2 3 4 5 6 | while True : # user_input = input('>') user_input = raw_input ( '>' ) print (user_input) if user_input.strip().lower() = = 'exit' : break |
上述程序在 Linux 环境下运行时,我们将无法使用任何的 Linux 快捷键,甚至在输入错误时,按退格删除内容都会出现问题:
下面,我们使用 prompt_toolkit
模块中的 prompt
函数改写上述程序:
1 2 3 4 5 | from __future__ import print_function from prompt_toolkit import prompt while True : user_input = prompt(u '>>' ) print (user_input) |
运行新的程序,你会发现,不仅可以实现退格删除,而且可以使用 Bash
下常用的快捷键:Ctrl + a
跳转到开头、Ctrl + e
跳转到末尾、Ctrl + k
删除光标到末尾的内容。
二. 实现查找历史命令
在 Bash 下,我们可以使用方向键中的 ↑
和 ↓
查看历史输入,或者使用 Ctrl + r
搜索历史命令:
在 Python 打造的交互式命令行中,使用 prompt_toolkit.history
我们可以很容易实现查找历史:
1 2 3 4 5 6 7 8 | from __future__ import print_function from __future__ import unicode_literals from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory while True : user_input = prompt( '>>>' , history = FileHistory( 'history.txt' )) print (user_input) |
运行结果:
上述历史输入将被保存至当前目录下的 history.txt
文件中,后续就可以使用查看或搜索历史命令了~
三. 根据历史输入自动提示
在上面是示例中我们实现了查看或搜索历史输入的功能,其实我们还可以更加充分地利用 history.txt
中记载的历史输入,在用户输入时进行提示。实现此功能只需要在调用 prompt
函数时指定 auto_suggest
的参数即可:
1 2 3 4 5 6 7 8 9 10 11 12 | from __future__ import print_function from __future__ import unicode_literals from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory while True : user_input = prompt( '>>>' , history = FileHistory( 'history.txt' ), auto_suggest = AutoSuggestFromHistory()) if user_input.strip().lower() = = 'exit' : break print (user_input) |
prompt_toolkit
将以暗色字体显示匹配的历史输入:
四. 实现输入的自动补全
所谓自动补全,即用户输入了关键字的一部分,我们的交互式程序能够根据已有的输入进行提示,用户可以使用 Tab 键补全选择提示的内容。以上功能,prompt_toolkit
提供了名为 WorldCompleter
的类来帮助我们实现。下面我们来模仿 MySQL 客户端的提示功能:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | from __future__ import print_function from __future__ import unicode_literals 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 True : user_input = prompt( 'SQL>' , history = FileHistory( 'history.txt' ), auto_suggest = AutoSuggestFromHistory(), completer = SQLCompleter) if user_input.strip().lower() = = 'exit' : break print (user_input) |
到此这篇关于Python 命令行 - prompt_toolkit 库的文章就介绍到这了
原文链接:https://blog.csdn.net/qq_15256443/article/details/122420681