Python使用Rich實現(xiàn)美化終端顯示效果
Rich
庫的功能就像它的名字一樣,使Python
編程更加豐富(rich),它幫助開發(fā)者在控制臺(命令行)輸出中創(chuàng)建豐富、多彩和具有格式化的文本。
本篇總結了如何使用Rich
庫讓我們的命令行工具更加美觀。
1. 安裝
通過pip
安裝:
pip install rich
使用下面的命令驗證是否安裝成功。
python -m rich
2. 應用示例
Rich的功能很多,下面通過代碼示例來演示其中主要的功能。
2.1. 美化 REPL 輸出
安裝python
之后,在命令行輸入python
,就可以進入python
的交互式命令行環(huán)境(REPL)。
因為python
是解釋性語言,所以可以在REPL環(huán)境中交互式的運行代碼:
注:REPL全稱: Read-Eval-Print-Loop (交互式解釋器)
默認的REPL
是沒有顏色的,使用Rich
可以美化REPL
的顯示,獲得更好的交互效果。
只需要導入Rich
庫的pretty
即可。
>>> from rich import pretty >>> pretty.install()
再次運行上面的代碼:
不同的數(shù)據(jù)類型會用不同的顏色來表示。
2.2. 查看對象信息
Rich
庫中還提供了一個還有用的功能,用來查看python
中各個變量或對象的詳細信息。
使用前導入 inspect
函數(shù)。
>>> from rich import inspect
對于變量,查看其概括信息的方式如下:
>>> inspect(lst_var)
查看其包含的方法:
>>> inspect(lst_var, methods=True)
對于對象,也是一樣:
# -*- coding: utf-8 -*- from rich import inspect class Sample: def __init__(self, name, age): self._name = name self._age = age def info(self): print("姓名: {}, 年齡: {}".format(self.name, self.age)) def set(self, name, age): self.name = name self.age = age def get(self): return {"name": self.name, "age": self.age} # 私有函數(shù) def _private(self): print("這是私有函數(shù)") if __name__ == "__main__": sa = Sample("harry", 33) # 顯示對象概要信息 inspect(sa) # 顯示對象方法信息 inspect(sa, methods=True) # 顯示對象方法和私有變量,私有函數(shù) inspect(sa, methods=True, private=True)
Rich
庫的inspect
函數(shù)讓我們在命令行中也可以獲得非常好的閱讀體驗。
2.3. 動態(tài)顯示內容
動態(tài)顯示在命令行中一直是個難點,而Rich
庫能幫助我們很容易的實現(xiàn)狀態(tài)和進度的動態(tài)顯示。
比如,如果有多個任務在執(zhí)行,可以用Rich
來動態(tài)顯示執(zhí)行的情況。
# -*- coding: utf-8 -*- from time import sleep from rich.console import Console console = Console() count = 5 tasks = [f"task {n}" for n in range(1, count + 1)] with console.status("") as status: num = 1 while tasks: status.update("[{}/{}] 已經(jīng)完成".format(num, count)) task = tasks.pop(0) sleep(1) num += 1 print("所有任務 全部完成!")
這樣就不用打印出很多行的日志信息,而是動態(tài)的顯示task
完成的情況。
還有一個動態(tài)的應用是進度條,進度條雖然不能提高程序的性能,但是它讓我們了解到程序大概運行到哪了,能夠減少等待的焦慮。
比如,傳輸大量文件或者下載大文件的過程中,沒有進度條的話,常常會擔心程序是不是卡住了。
下面是一個模擬文件傳輸中使用進度條的示例:
# -*- coding: utf-8 -*- import time from rich.progress import Progress # 模擬2個文件,一個是文件名,一個是文件大小 files = [("windows.iso", 24000), ("debian.iso", 17000)] with Progress() as progress: tasks = [] for f in files: task_id = progress.add_task("copy {}".format(f[0]), filename=f[0], start=False) progress.update(task_id, total=f[1]) progress.start_task(task_id) # 模擬讀取文件,每次讀取1024字節(jié) total = f[1] buffer = 1024 while total > 0: read_bytes = 0 if total > buffer: read_bytes = buffer total -= buffer else: read_bytes = total total = 0 progress.update(task_id, advance=read_bytes) time.sleep(0.2) progress.console.log("{} 傳輸完成!".format(f[0])) progress.stop_task(task_id)
2.4. 復雜結構顯示
Rich
庫還可以幫助我們在控制臺顯示一些結構化的內容。
2.4.1. 表格
表格是最常用的一種表現(xiàn)形式,也是最常用的一種展示數(shù)據(jù)的方式。
# -*- coding: utf-8 -*- from rich.console import Console from rich.table import Table table = Table(title="國內生產(chǎn)總值指數(shù)") table.add_column("年份", justify="left", style="cyan", no_wrap=True) table.add_column("指標", style="magenta") table.add_column("數(shù)值", justify="right", style="green") table.add_row("2022年", "國民總收入指數(shù)", "4432.1") table.add_row("2021年", "國民總收入指數(shù)", "4319.7") table.add_row("2020年", "國民總收入指數(shù)", "3979.1") table.add_row("2019年", "國民總收入指數(shù)", "3912.1") console = Console() console.print(table)
2.4.2. 樹形
樹形結構也是常用的結構,比如展示文件夾結構:
# -*- coding: utf-8 -*- from rich.tree import Tree from rich import print # 根節(jié)點 tree = Tree("/") # usr 分支 usr = tree.add("usr") fonts = usr.add("fonts") bin = usr.add("bin") lib = usr.add("lib") # home 分支 home = tree.add("home") git = home.add("git") python = home.add("python") golang = home.add("golang") # projects 分支 projects = home.add("projects") samples = projects.add("samples") work = projects.add("work") print(tree)
2.5. 文檔和代碼顯示
在IT
行業(yè)內,markdown文檔和代碼幾乎是繞不開的2個東西。
然而,直接在命令行中原樣顯示的markdown和代碼的話,是很難閱讀的。
利用Rich
庫,可以幫助我們解析markdown的標記,高亮不同編程語言的代碼,從而在命令行中獲得良好的閱讀體驗。
# -*- coding: utf-8 -*- from rich.console import Console from rich.markdown import Markdown md_sample = """這是一份[Markdown][1]的語法介紹。 # 段落 一個段落是由一個或多個連續(xù)的行構成,段落間靠一個或以上視覺上的空行劃分。 這是一個段落。它有兩個句子。 這是另一個段落。它也有 兩個句子。 ## 代碼 `print("hello")` ### 列表 * 無序(沒有編號的)列表中的一項 * 一個子項,要以一個制表符或者4個空格縮進 * 無序列表中的另一個項 1. 有序(排好序,有編號的)列表中的一項 1. 有序列表中的另一個項 [1]: http://daringfireball.net/projects/markdown/ """ console = Console() markdown = Markdown(md_sample) console.print(markdown)
可以看出,不同的markdown標記會解析成不同的顯示效果。
同樣,對于不同的代碼,也可以高亮顯示:
# -*- coding: utf-8 -*- from rich.console import Console from rich.syntax import Syntax py_code = """ def hello(name): print("hello ", name) hello("world") """ java_code = """ public class HelloWorld { public static void main(String[] args) { System.out.println("Hello,World!"); } } """ c_code = """ #include <stdio.h> int main() { printf("Hello,World!"); return 1; } """ console = Console() console.print("========================") console.print("[green]python 代碼") console.print("========================") syntax = Syntax(py_code, "python", theme="monokai", line_numbers=True) console.print(syntax) console.print("========================") console.print("[blue]java 代碼") console.print("========================") syntax = Syntax(java_code, "java", theme="monokai", line_numbers=True) console.print(syntax) console.print("========================") console.print("[red]c 代碼") console.print("========================") syntax = Syntax(c_code, "c", theme="monokai", line_numbers=True) console.print(syntax)
這里只演示了3種代碼,但是Rich
可以支持幾乎所有主流的代碼。
3. 總結
總的來說,Python Rich
庫是一個強大的工具,可以讓Python
開發(fā)者在命令行環(huán)境中擁有更加豐富和強大的輸出能力,使得數(shù)據(jù)呈現(xiàn)更加直觀,增強了代碼的可讀性和調試效率。
本篇演示了一些常用的功能,關于Rich
庫的其他功能和每個功能的細節(jié)可以參考其官方文檔:https://rich.readthedocs.io/en/latest/
以上就是Python使用Rich實現(xiàn)美化終端顯示效果的詳細內容,更多關于Python Rich美化終端顯示的資料請關注腳本之家其它相關文章!
相關文章
python實現(xiàn)網(wǎng)站用戶名密碼自動登錄功能
最近接到這樣的需求通過網(wǎng)頁用戶認證登錄實現(xiàn)上網(wǎng),如何實現(xiàn)網(wǎng)站自動登錄功能呢,接下來小編給大家?guī)砹藀ython實現(xiàn)網(wǎng)站用戶名密碼自動登錄功能,需要的朋友可以參考下2019-08-08數(shù)據(jù)庫操作入門PyMongo?MongoDB基本用法
這篇文章主要為大家介紹了數(shù)據(jù)庫操作入門PyMongo MongoDB基本用法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11Python+OpenAI?Whisper實現(xiàn)視頻生成字幕
這篇文章主要為大家詳細介紹了如何利用Python和OpenAI?Whisper實現(xiàn)視頻生成字幕功能,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下2024-11-11深度學習TextRNN的tensorflow1.14實現(xiàn)示例
這篇文章主要介紹了深度學習TextRNN的tensorflow1.14實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01