A library for building high-quality Python command-line user interfaces
Jan 17, 2024 am 11:27 AMIn the second tutorial in this two-part series about terminal programs with great command-line interfaces, we'll discuss Prompt, Toolkit, Click, Pygments, and Fuzzy Finder.
This is the second tutorial in my two-part series about terminal programs with great command line interfaces. In the first article, we discussed some of the features that make command line applications a joy to use. In this second article, we’ll look at how to implement these features using some of Python’s libraries.
I plan to implement it in less than 20 lines of Python code. let's start.
Python Prompt ToolkitI am accustomed to calling this library the Swiss Army Knife of command line applications. It can be used as a replacement for readline, curses, etc. Let's first install this library and then start the tutorial:
pip install prompt_toolkit
We start with a simple REPL (LCTT Annotation: REPL - Read-Eval-Print Loop, interactive development environment). A typical REPL receives user input, performs an operation, and outputs the result. For example, in our example, we are going to implement a REPL with "echo" functionality. It simply prints out the user's input as is:
REPLfrom prompt_toolkit import prompt while 1: user_input = prompt('>') print(user_input)
This is all the code to implement REPL. It reads the user's input and then prints out the user's input. The prompt function used in this code comes from the prompt_toolkit library, which is a replacement for the readline library.
Command HistoryTo enhance the functionality of our REPL, we can add command history:
from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory while 1: user_input = prompt('>', history=FileHistory('history.txt'), ) print(user_input)
We just added a persistent command history to the REPL. Now we can use the up/down arrows to browse the command history and Ctrl-R to search the command history. It meets the basic guidelines of the command line.
Automatic recommendationIn the first tutorial, one of the discoverability techniques I talked about was automatically recommending historical commands. (I first saw this feature in fish shell) Let's add this feature to our REPL:
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)
We just need to add a new parameter to the prompt() API call. Now we have a fish shell-style REPL that automatically recommends historical commands.
AutocompleteNow, let’s enhance tab completion with autocompletion. It pops up possible command recommendations as the user starts typing.
REPL How to make recommendations? We use a dictionary to recommend possible items.
For example, let’s implement a REPL for SQL. We can store SQL keywords in the auto-complete dictionary. Let's see how this is done:
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)
Again, we simply used prompt-toolkit's built-in completion feature called WordCompleter, which matches user input with possible recommended dictionaries. , and then provide a list.
Now, we have a REPL with auto-completion, fish shell-style historical command recommendations, and up/down browsing history. Implementing these features took less than 10 lines of actual code.
ClickClick is a command line creation toolkit that makes it easier to parse command line option parameters and constants for programs. We will not discuss how to use Click as a parameter parser here. Instead, we'll look at some of the features that Click comes with.
Install Click:
pip install click
Paginators are utilities on Unix systems that are capable of displaying very long output one page at a time. Some examples of pagers include less, more, most, etc. Displaying the output of a command through a pager is not only a friendly design, but also a necessity.
讓我們進(jìn)一步改進(jìn)前面的例子。我們不再使用默認(rèn)print()語句,取而代之的是click.echo_via_pager()。它將會(huì)把輸出通過分頁器發(fā)送到標(biāo)準(zhǔn)輸出。這是平臺(tái)無關(guān)的,因此在 Unix 系統(tǒng)或 Windows 系統(tǒng)上均能工作。如果必要的話,click_via_pager 會(huì)嘗試使用一個(gè)合適的默認(rèn)分頁器來輸出,從而能夠顯示代碼高亮。
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 import click SQLCompleter = WordCompleter(['select', 'from', 'insert', 'update', 'delete', 'drop'], ignore_case=True) while 1: user_input = prompt(u'SQL>', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=SQLCompleter, ) click.echo_via_pager(user_input)編輯器
在我前面的文章中一個(gè)值得一提的細(xì)節(jié)是,當(dāng)命令過于復(fù)雜的時(shí)候進(jìn)入編輯器來編輯。Click 有一個(gè)簡單的 API 能夠打開編輯器,然后把在編輯器中輸入的文本返回給應(yīng)用。
import click message = click.edit()Fuzzy Finder
Fuzzy Finder 是一種通過少量輸入來為用戶減少推薦的方法。幸運(yùn)的是,有一個(gè)庫可以實(shí)現(xiàn) Fuzzy Finder 。讓我們首先安裝這個(gè)庫:
pip install fuzzyfinder
Fuzzy Finder的 API 很簡單。用戶向它傳遞部分字符串和一系列可能的選擇,然后,F(xiàn)uzzy Finder將會(huì)返回一個(gè)與部分字符串匹配的列表,這一列表是通過模糊算法根據(jù)相關(guān)性排序得出的。比如:
>>> from fuzzyfinder import fuzzyfinder >>> suggestions = fuzzyfinder('abc', ['abcd', 'defabca', 'aagbec', 'xyz', 'qux']) >>> list(suggestions) ['abcd', 'defabca', 'aagbec']
現(xiàn)在我們有了fuzzyfinder>,讓我們把它加入到我們的 SQL REPL 中。方法是我們自定義一個(gè)completer而不是使用來自prompt-toolkit庫的WordCompleter。比如:
from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import Completer, Completion import click from fuzzyfinder import fuzzyfinder SQLKeywords = ['select', 'from', 'insert', 'update', 'delete', 'drop'] class SQLCompleter(Completer): def get_completions(self, document, complete_event): word_before_cursor = document.get_word_before_cursor(WORD=True) matches = fuzzyfinder(word_before_cursor, SQLKeywords) for m in matches: yield Completion(m, start_position=-len(word_before_cursor)) while 1: user_input = prompt(u'SQL>', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=SQLCompleter(), ) click.echo_via_pager(user_input)Pygments
現(xiàn)在,讓我們給用戶輸入添加語法高亮。我們正在搭建一個(gè) SQL REPL,如果具有彩色高亮的 SQL 語句,這會(huì)很棒。
Pygments是一個(gè)提供語法高亮的庫,內(nèi)建支持超過 300 種語言。添加語法高亮能夠使應(yīng)用變得彩色化,從而能夠幫助用戶在執(zhí)行程序前發(fā)現(xiàn) SQL 中存在的錯(cuò)誤,比如拼寫錯(cuò)誤、引號(hào)不匹配或括號(hào)不匹配。
首先,安裝Pygments:
pip install pygments
讓我們使用Pygments來為 SQL REPL 添加顏色:
from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import Completer, Completion import click from fuzzyfinder import fuzzyfinder from pygments.lexers.sql import SqlLexer SQLKeywords = ['select', 'from', 'insert', 'update', 'delete', 'drop'] class SQLCompleter(Completer): def get_completions(self, document, complete_event): word_before_cursor = document.get_word_before_cursor(WORD=True) matches = fuzzyfinder(word_before_cursor, SQLKeywords) for m in matches: yield Completion(m, start_position=-len(word_before_cursor)) while 1: user_input = prompt(u'SQL>', history=FileHistory('history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=SQLCompleter(), lexer=SqlLexer, ) click.echo_via_pager(user_input)
Prompt Toolkit能夠和Pygments一同很好的工作。我們把Pygments提供的SqlLexer加入到來自prompt-toolkit的prompt中?,F(xiàn)在,所有的用戶輸入都會(huì)被當(dāng)作 SQL 語句,并進(jìn)行適當(dāng)著色。
結(jié)論我們的“旅途”通過創(chuàng)建一個(gè)強(qiáng)大的 REPL 結(jié)束,這個(gè) REPL 具有常見的 shell 的全部特性,比如歷史命令,鍵位綁定,用戶友好性比如自動(dòng)補(bǔ)全、模糊查找、分頁器支持、編輯器支持和語法高亮。我們僅用少于 20 行 Python 代碼就實(shí)現(xiàn)了這個(gè) REPL 。
不是很簡單嗎?現(xiàn)在,你沒有理由不會(huì)寫一個(gè)自己的命令行應(yīng)用了。
The above is the detailed content of A library for building high-quality Python command-line user interfaces. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The key to installing dual systems in Linux and Windows is partitioning and boot settings. 1. Preparation includes backing up data and compressing existing partitions to make space; 2. Use Ventoy or Rufus to make Linux boot USB disk, recommend Ubuntu; 3. Select "Coexist with other systems" or manually partition during installation (/at least 20GB, /home remaining space, swap optional); 4. Check the installation of third-party drivers to avoid hardware problems; 5. If you do not enter the Grub boot menu after installation, you can use boot-repair to repair the boot or adjust the BIOS startup sequence. As long as the steps are clear and the operation is done properly, the whole process is not complicated.

The key to enabling EPEL repository is to select the correct installation method according to the system version. First, confirm the system type and version, and use the command cat/etc/os-release to obtain information; second, enable EPEL through dnfinstallepel-release on CentOS/RockyLinux, and the 8 and 9 version commands are the same; third, you need to manually download the corresponding version of the .repo file and install it on RHEL; fourth, you can re-import the GPG key when encountering problems. Note that the old version may not be supported, and you can also consider enabling epel-next to obtain the test package. After completing the above steps, use dnfrepolist to verify that the EPEL repository is successfully added.

Newbie users should first clarify their usage requirements when choosing a Linux distribution. 1. Choose Ubuntu or LinuxMint for daily use; programming and development are suitable for Manjaro or Fedora; use Lubuntu and other lightweight systems for old devices; recommend CentOSStream or Debian to learn the underlying principles. 2. Stability is preferred for UbuntuLTS or Debian; you can choose Arch or Manjaro to pursue new features. 3. In terms of community support, Ubuntu and LinuxMint are rich in resources, and Arch documents are technically oriented. 4. In terms of installation difficulty, Ubuntu and LinuxMint are relatively simple, and Arch is suitable for those with basic needs. It is recommended to try it first and then decide.

The steps to add a new hard disk to the Linux system are as follows: 1. Confirm that the hard disk is recognized and use lsblk or fdisk-l to check; 2. Use fdisk or parted partitions, such as fdisk/dev/sdb and create and save; 3. Format the partition to a file system, such as mkfs.ext4/dev/sdb1; 4. Use the mount command for temporary mounts, such as mount/dev/sdb1/mnt/data; 5. Modify /etc/fstab to achieve automatic mount on the computer, and test the mount first to ensure correctness. Be sure to confirm data security before operation to avoid hardware connection problems.

Have problems uploading files in Google Chrome? This may be annoying, right? Whether you are attaching documents to emails, sharing images on social media, or submitting important files for work or school, a smooth file upload process is crucial. So, it can be frustrating if your file uploads continue to fail in Chrome on Windows PC. If you're not ready to give up your favorite browser, here are some tips for fixes that can't upload files on Windows Google Chrome 1. Start with Universal Repair Before we learn about any advanced troubleshooting tips, it's best to try some of the basic solutions mentioned below. Troubleshooting Internet connection issues: Internet connection

Logs in Linux systems are usually stored in the /var/log directory, which contains a variety of key log files, such as syslog or messages (record system logs), auth.log (record authentication events), kern.log (record kernel messages), dpkg.log or yum.log (record package operations), boot.log (record startup information); log content can be viewed through cat, tail-f or journalctl commands; application logs are often located in subdirectories under /var/log, such as Apache's apache2 or httpd directory, MySQL log files, etc.; at the same time, it is necessary to note that log permissions usually require s

sudo stands for "substituteuserdo" or "superuserdo", allowing users to run commands with permissions of other users (usually root). Its core uses include: 1. Perform system-level operations such as installing software or editing system files; 2. Accessing protected directories or logs; 3. Manage services such as restarting nginx; 4. Modify global settings such as /etc/hosts. When using it, the system will check the /etc/sudoers configuration and verify the user password, provide temporary permissions instead of continuously logging in as root, ensuring security. Best practices include: only when necessary, avoid blindly executing network commands, editing sudoers files with visudo, and considering continuous operations.

To manage Linux user groups, you need to master the operation of viewing, creating, deleting, modifying, and user attribute adjustment. To view user group information, you can use cat/etc/group or getentgroup, use groups [username] or id [username] to view the group to which the user belongs; use groupadd to create a group, and use groupdel to specify the GID; use groupdel to delete empty groups; use usermod-aG to add users to the group, and use usermod-g to modify the main group; use usermod-g to remove users from the group by editing /etc/group or using the vigr command; use groupmod-n (change name) or groupmod-g (change GID) to modify group properties, and remember to update the permissions of relevant files.
