Skip to content

[Linux] 彩色打印輸出 rich-cli 指令筆記

Introduction

rich-cli 是一個基於 Python rich 套件的命令列工具,也就是說,我們可以不必撰寫 Python 程式碼就直接輸出彩色終端機的文字結果。

不過在終端機中還是直接被寫作 rich。但重點是,我們可以替 Markdown 和 JSON 文件提供渲染,也能標記和格式化各式各樣的文本內容。

本篇文章的內容主要來自 rich-cli 的 GitHub,相關連結放置文末。下面我們首先來看看該如何安裝吧!


安裝方式

以下,我們有幾種選擇可以安裝 rich-cli


Windows / Linux

我們可以透過使用 pipx 安裝。pipx 是一個用於管理 Python 程式的工具,它允許您在虛擬環境中安裝並運行 Python 應用程序,而不會影響到全局環境。

pipx install rich-cli



MacOS

在 MacOS 的環境中,我們自然就是透過 Homebrew 來安裝 rich-cli 了。

brew install rich



Universal

另外一個通用的方法,就是直接使用 pip 安裝 python 的 rich-cli 套件:

python -m pip install rich-cli


或使用 conda 或 mamba:

mamba install -c conda-forge rich-cli

使用方法

選擇了上述任一種安裝方式後,現在我們應該在命令列中擁有 rich 指令了。首先我們來查看使用方法:

rich --help


Output:

                               Rich CLI v1.8.0 🤑                               
                                                                                
                    Rich text and formatting in the terminal                    
                                                                                
Usage: rich [OPTIONS] <PATH,TEXT,URL, or '-'>

╭─ Options ────────────────────────────────────────────────────────────────────╮
│  -p  --print                          Print console markup. See              │
│                                       https://rich.readthedocs.io/en/lates…  │
│  -u  --rule                           Display a horizontal rule.             │
│  -j  --json                           Display as JSON.                       │
│  -m  --markdown                       Display as markdown.                   │
│      --rst                            Display restructured text.             │
│      --csv                            Display CSV as a table.                │
│      --ipynb                          Display Jupyter notebook.              │
│      --syntax                         Syntax highlighting.                   │
│      --inspect                        Inspect a python object.               │
│  -h  --head LINES                     Display first LINES of the file        │
│                                       (requires --syntax or --csv).          │
│  -t  --tail LINES                     Display last LINES of the file         │
│                                       (requires --syntax or --csv).          │
│  -j  --emoji                          Enable emoji code. e.g. :sparkle:      │
│  -l  --left                           Align to left.                         │
│  -r  --right                          Align to right.                        │
│  -c  --center                         Align to center.                       │
│  -L  --text-left                      Justify text to left.                  │
│  -R  --text-right                     Justify text to right.                 │
│  -C  --text-center                    Justify text to center.                │
│  -F  --text-full                      Justify text to both left and right    │
│                                       edges.                                 │
│      --soft                           Enable soft wrapping of text           │
│                                       (requires --print).                    │
│  -e  --expand                         Expand to full width (requires         │
│                                       --panel).                              │
│  -w  --width SIZE                     Fit output to SIZE characters.         │
│  -W  --max-width SIZE                 Set maximum width to SIZE characters.  │
│  -s  --style STYLE                    Set text style to STYLE.               │
│      --rule-style STYLE               Set rule style to STYLE.               │
│      --rule-char CHARACTER            Use CHARACTER to generate a line with  │
│                                       --rule.                                │
│  -d  --padding TOP,RIGHT,BOTTOM,LEFT  Padding around output. 1, 2 or 4       │
│                                       comma separated integers, e.g. 2,4     │
│  -a  --panel BOX                      Set panel type to BOX. ascii, ascii2,  │
│                                       double, heavy, none, rounded, square   │
│  -S  --panel-style STYLE              Set the panel style to STYLE           │
│                                       (requires --panel).                    │
│      --theme THEME                    Set syntax theme to THEME. See         │
│                                       https://pygments.org/styles/           │
│  -n  --line-numbers                   Enable line number in syntax.          │
│  -g  --guides                         Enable indentation guides in syntax    │
│                                       highlighting                           │
│  -x  --lexer LEXER                    Use LEXER for syntax highlighting.     │
│                                       See https://pygments.org/docs/lexers/  │
│  -y  --hyperlinks                     Render hyperlinks in markdown.         │
│      --no-wrap                        Don't word wrap syntax highlighted     │
│                                       files.                                 │
│      --title TEXT                     Set panel title to TEXT.               │
│      --caption TEXT                   Set panel caption to TEXT.             │
│      --force-terminal                 Force terminal output when not         │
│                                       writing to a terminal.                 │
│  -o  --export-html PATH               Write HTML to PATH.                    │
│      --export-svg PATH                Write SVG to PATH.                     │
│      --pager                          Display in an interactive pager.       │
│  -v  --version                        Print version and exit.                │
│      --help                           Show this message and exit.            │
╰──────────────────────────────────────────────────────────────────────────────╯
♥ https://www.textualize.io                                                     


語法高亮

現在我們嘗試來對一個帶有程式碼的文件進行彩色輸出,也就是關鍵字高亮(highlight)。我們要在 rich 指令後加入文件的路徑。

rich example.py


若要啟用行號,可以嘗試添加 --line-number-n

若是添加 --guides-g 則是啟用縮進指南。

rich example.py -n -g


若是有想要使用的主題,可以使用 --theme 來添加。我沒有認真去比對,不過我想主題名稱跟顏色搭配和 pygments 是相同的。

rich example.py --theme dracula


如果不想每次都指定主題,而是讓喜歡的主題變為預設配置,那麼我們可以設定 RICH_THEME 環境變數。以下命令等同於上面的命令:

RICH_THEME=dracula rich loop.py


也就是說,你可以把環境變數跟你的終端機設置綁定在一起,比方說在 ~/.bashrc 中寫入這個環境變數。

在默認情況下,如果 rich 發現行長度超過可用寬度,它將自動換行。我們可以使用 --no-wrap 關閉此行為;另外, rich 也會嘗試從文件名來推測文件格式,如果想要覆蓋自動檢測的語法分析器(比方說明明是 C++ 的程式但是 rich 卻搞錯成了 python,一般是若是副檔名正確是不會解析錯誤的),可以使用 --lexer-x 開關顯式設置。


Markdown

添加 --markdown-m 便能渲染 markdown 語法的文件。當然如果文件是以 .md 為副檔名,則會自動檢測 markdown。

rich README.md


若我們的終端機還支援顯示超連結的話,我們也可以添加 --hyperlinks-y,這將輸出超連結而不是完整的 URL。

rich README.md --hyperlinks



Jupyter notebook

在做資料分析時,jupyter notebook 是非常好用的編輯器,.ipynb 也支援我們隨時以單元(cell)來一小片段、一小片段地測試程式碼。

而在 rich-cli 中,自然也支援 jupyter notebook 的格式渲染。如果文件是以 .ipynb 為副檔名,則會自動檢測;如果不是以這為副檔名,也只需要添加 --ipynb 就能成功渲染。

rich example.ipynb




JSON

使用 --json-j 能夠讓以 JSON 格式渲染文件。

rich example.json



CSV

rich 指令也可以將 CSV或 TSV 的內容顯示為表格。

rich example.csv



Rules

使用 --rule-u 能夠渲染一條水平線,並且我們能夠使用 --rule-style 來指定這條水平線的樣式,也能以 --rule-char 來設置中間放置的文字。

rich "Hello [b]World[/b]!" --rule
rich "Hello [b]World[/b]!" --rule --rule-style "red"
rich "Hello [b]World[/b]!" --rule --rule-style "red" --rule-char "="



Pager

添加 --pager 就能以內建的分頁器(pager)來顯示文件內容。使用滑鼠、Page Up/Down、Home、End 或滾動條就能滾動頁面。如果想要使用使用 vi/vim 的移動方式(j、k、ctrl_d、ctrl-u)也是支援的。

rich example.py -n -g --theme monokai --pager



Network

rich 指令也可以直接渲染網路上的文件並呈現在終端機上,只要那個文件是可以存取的。我們只需要輸入一個以 http:// 或 https:// 開頭的 URL。這裡我們自然是直接以官方 GitHub 倉庫的 README.md 來做範例。

rich https://raw.githubusercontent.com/Textualize/rich-cli/main/README.md --markdown



Exporting

除了在終端機中渲染,rich 也可以將其渲染結果以 HTML 格式輸出。我們只需要加入 --export-html-o,然後輸入儲存的文件路徑。

rich README.md -o readme.html



執行後,我們應該會看到一份名為 readme.html 的文件。


Rich Printing

如果使用 --print-p 選項,那麼我們會把第一個參數當作命令列標記,這樣可以添加如 bbcode 的樣式。實際範例如下:

rich "Hello, [bold magenta]World[/]!" --print



Soft wrapping

rich 指令預設會在適當位置來對文本進行換行,如果不需要此項設定,則可以使用 --soft 來禁用此默認設定。


Reading from Stdin

如果我們要從一個進程管線(pipe)來取得給 rich 的輸入,比方說從 cat 指令,我們可以使用以下指令格式:

请注意,当 rich 不直接写入终端时,它将禁用 ansi 颜色代码,因此您可能需要添加 --force-terminal-F 来告诉 rich 保留 ansi 代码输出。

cat README.md | rich - --markdown --force-terminal


需要注意的是,這樣的使用方式會導致 rich 默認禁用 ANSI 顏色碼,因此需要添加如 --force-terminal-F 來告訴 rich 保留 ANSI 碼的輸出。


通用選項

除此之外,還有許多通用的參數可以讓我們修改要渲染輸出的內容。之所以說是『通用』選項,是因為這些選項可以和上述的各種選項同時使用,而不會發生衝突。

樣式

我們可以使用 --style-s 來設置輸出樣式。

rich "Hello, [b]World[/b]!" --print --style "on blue"



對齊

我們可以使用 --left--center--right 選項來將輸出對齊到我們想要的位置;也可以使用縮寫:-l-c-r

rich "Hello [b]World[/b]!" --print --center



寬度

我們也可以使用 --width-w 來設置輸出所允許的寬度。

rich "I must not fear. Fear is the mind-killer. Fear is the little-death that brings total obliteration." -p -w 40



文本對齊

如果是要對整個文本進行對齊,則可以使用 --text-left--text-right--text-center--text-full;比較精簡的方式是單個字元選項:-L-R-C-F

--left--text-left 的區別在指定輸出寬度時較明顯。

以下是一個範例,我們指定了寬度為 40 (-w 40),並使用 -c 來對齊。

rich "I must not fear. Fear is the mind-killer. Fear is the little-death that brings total obliteration." -p -w 40 -c -L
rich "I must not fear. Fear is the mind-killer. Fear is the little-death that brings total obliteration." -p -w 40 -c -R
rich "I must not fear. Fear is the mind-killer. Fear is the little-death that brings total obliteration." -p -w 40 -c -C
rich "I must not fear. Fear is the mind-killer. Fear is the little-death that brings total obliteration." -p -w 40 -c -F



填充

我們可以使用 --padding-d 在輸出周圍填充。

rich "Hello [b]World[/b]!" -p -c --padding 3 --style "on blue"



面板

我們可以使用 --panel-a 在文本周圍繪製面板,且面被可以採用多種樣式。

rich "Hello, [b]World[/b]!" -p -a heavy


基本上,rich-cli 是一個強大的命令列工具,能夠在終端機中生成美觀的輸出,如高亮顯示、markdown、json、jupyter notebook、csv…… 到文本對齊方式和樣式設置。這些功能能讓我們終端機的輸出不再呆板一致。


References


Read More

Tags:

Leave a Reply