diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index 4003bd24b..95daf9d31 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -7,4 +7,4 @@ jobs: - uses: actions/checkout@v2 - run: python3 -m pip install codespell - run: codespell --ignore-words-list="ba,fo,hel,revered,womens" - --skip="./README.de.md,./README.es.md,./README.sv.md,*.svg" + --skip="./README.de.md,./README.es.md,./README.sv.md,./README.fr.md,./README.de-ch.md,./README.hi.md,./README.pt-br.md,*.svg" diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 9b4bcab5f..98b80f1c3 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -12,5 +12,6 @@ The following people have contributed to the development of Rich: - [Alexander Mancevice](https://github.com/amancevice) - [Will McGugan](https://github.com/willmcgugan) - [Nathan Page](https://github.com/nathanrpage97) +- [Kylian Point](https://github.com/p0lux) - [Clément Robert](https://github.com/neutrinoceros) - [Gabriele N. Tornetta](https://github.com/p403n1x87) diff --git a/README.cn.md b/README.cn.md index 50b43da3b..5ad391494 100644 --- a/README.cn.md +++ b/README.cn.md @@ -1,10 +1,14 @@ -# Rich - +[![Downloads](https://pepy.tech/badge/rich/month)](https://pepy.tech/project/rich) [![PyPI version](https://badge.fury.io/py/rich.svg)](https://badge.fury.io/py/rich) [![codecov](https://codecov.io/gh/willmcgugan/rich/branch/master/graph/badge.svg)](https://codecov.io/gh/willmcgugan/rich) [![Rich blog](https://img.shields.io/badge/blog-rich%20news-yellowgreen)](https://www.willmcgugan.com/tag/rich/) [![Twitter Follow](https://img.shields.io/twitter/follow/willmcgugan.svg?style=social)](https://twitter.com/willmcgugan) +![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg) + +[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) • [Français readme](https://github.com/willmcgugan/rich/blob/master/README.fr.md) • [Schwizerdütsch readme](https://github.com/willmcgugan/rich/blob/master/README.de-ch.md) • [हिन्दी readme](https://github.com/willmcgugan/rich/blob/master/README.hi.md) + • [Português brasileiro readme](https://github.com/willmcgugan/rich/blob/master/README.pt-br.md) + Rich 是一个 Python 库,可以为您在终端中提供富文本和精美格式。 [Rich API](https://rich.readthedocs.io/en/latest/) 可以很容易的在终端输出添加各种颜色和不同风格。Rich 还可以绘制漂亮的表格,进度条,markdown,突出显示语法的源代码及回溯等等,不胜枚举。 diff --git a/README.de-ch.md b/README.de-ch.md new file mode 100644 index 000000000..5bc8ddcc9 --- /dev/null +++ b/README.de-ch.md @@ -0,0 +1,445 @@ +[![Downloads](https://pepy.tech/badge/rich/month)](https://pepy.tech/project/rich) +[![PyPI version](https://badge.fury.io/py/rich.svg)](https://badge.fury.io/py/rich) +[![codecov](https://codecov.io/gh/willmcgugan/rich/branch/master/graph/badge.svg)](https://codecov.io/gh/willmcgugan/rich) +[![Rich blog](https://img.shields.io/badge/blog-rich%20news-yellowgreen)](https://www.willmcgugan.com/tag/rich/) +[![Twitter Follow](https://img.shields.io/twitter/follow/willmcgugan.svg?style=social)](https://twitter.com/willmcgugan) + +![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg) + +[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) • [Français readme](https://github.com/willmcgugan/rich/blob/master/README.fr.md) • [Schwizerdütsch readme](https://github.com/willmcgugan/rich/blob/master/README.de-ch.md) • [हिन्दी readme](https://github.com/willmcgugan/rich/blob/master/README.hi.md) + • [Português brasileiro readme](https://github.com/willmcgugan/rich/blob/master/README.pt-br.md) + +Rich isch ä Python Library för _rich_ Text ond ganz schöni formatiärig im Törminäl + +D [Rich API](https://rich.readthedocs.io/en/latest/) machts ganz eifach zom Farbä ond Stiil zu de Törminälusgob hinzu z füäge. Rich cha au schöni Tabelle, Progressbare, Markdown, Syntax hervorhebe, Tracebäcks und meh darstelle — fix fertig usem Böxli. + +![Features](https://github.com/willmcgugan/rich/raw/master/imgs/features.png) + +E Video Iifüärig öber Rich geds onder [calmcode.io](https://calmcode.io/rich/introduction.html) vo [@fishnets88](https://twitter.com/fishnets88). + +Lueg was [anderi öber Rich säged](https://www.willmcgugan.com/blog/pages/post/rich-tweets/). + +## Kompatibilität + +Rich funktioniert mit Linux, OSX ond Windows. True color / emoji funktioniert mit em neue Windows Törminäl, s klassische Törminäl isch of 16 Farbe limitiärt. Rich brucht Pzthon 3.6.1 oder neuer. + +Rich funktioniert mit [Jupyter notebooks](https://jupyter.org/) ohni irgendwelchä zuäsätzloche konfiguration. + +## Installation + +Installation mit `pip` oder mit dim liäblings PyPi Päckli-Mangager. + +``` +pip install rich +``` + +Für das do us zum d Rich usgob im Törminäl z teste: + +``` +python -m rich +``` + +## Rich Print + +Zom ohni Ufwand Rich Usgob zu dinnere Applikation hinzuäfüäge, chasch eifach d [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start) Methodä importiäre, weli di glich Signatuur hed wiä d Builtin Python Funktion. Versuech das: + +```python +from rich import print + +print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals()) +``` + +![Hello World](https://github.com/willmcgugan/rich/raw/master/imgs/print.png) + +## Rich REPL + +Rich cha i de Python REPL installiert werde so dass irgend e Datestruktuur hübsch usgeh ond Highlighted wird. + +```python +>>> from rich import pretty +>>> pretty.install() +``` + +![REPL](https://github.com/willmcgugan/rich/raw/master/imgs/repl.png) + +## Console bruchä + +Für meh kontrolle öber de Törminäl inhalt, importiär und instanziär e [Console](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console) Objekt. + +```python +from rich.console import Console + +console = Console() +``` + +S Console Objekt hät e `print` Methode mitäre absichtloch gliche Schnittstell wiä d Builtin `print` Funktion. Do es Bispiil wiä mos brucht: + +```python +console.print("Hello", "World!") +``` + +Wiä erwartet wird `"Hello World!"` im Törminäl usgeh. Beach das im gägesatz zu de Builtin `print` Funktion, Rich de text so ombricht das es id Törminäl breiti ine passt. + +Es ged es paar Wäg zom Farb und Stiil zu de Usgob hinzuä z füäge. Me cha en stiil a de ganze Usgob zuäwiise i dem mo s Schlösselwortargument `style` verwendet. Do es Bispiil: + +```python +console.print("Hello", "World!", style="bold red") +``` + +D Usgob gsiät öppe ä so us: + +![Hello World](https://github.com/willmcgugan/rich/raw/master/imgs/hello_world.png) + +Da isch guät für d Gstalltig vom Text pro Liniä. Vör ä granularäri Gstalltig hed Rich e spezielli Markup mitäre ähnloche Befehlsufbau wiä [bbcode](https://en.wikipedia.org/wiki/BBCode). Do es Bispiil: + +```python +console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].") +``` + +![Console Markup](https://github.com/willmcgugan/rich/raw/master/imgs/where_there_is_a_will.png) + +Du chasch mitmäne Console Objekt mit wenig Ufwand aasprechendi Usgob erziile. Lueg do d [Console API](https://rich.readthedocs.io/en/latest/console.html) Dokumentation für d Details a. + +## Rich Inspect + +Rich hät e [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) Funktion wo cha Bricht öber jeglochi Python Objekt, wie Class, Instanz oder Builtin erstelle. + +```python +>>> my_list = ["foo", "bar"] +>>> from rich import inspect +>>> inspect(my_list, methods=True) +``` + +![Log](https://github.com/willmcgugan/rich/raw/master/imgs/inspect.png) + +Lueg do d [inspect Dokumentation](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect) für d Details a. + +# Rich Library + +Rich häd ä Aazahl vo integriäte _renderables_ wo du chasch verwende zum eleganti Usgobe i dinner e CLI generiäre ond der hälfed bim debugge vo dim Code. + +Drock of di folgende Öberschrifte für d Details: + +
+Log + +S Console Objekt hät e `log()` Methode wo verglichbar zu de `print()` Schnittstell isch aber zuäsätzloch no e Spaltä för di aktuäll Zitt und d Datai mit de Zille wo de Ufruäf macht us git. Standartmässig tuät Rich es Syntax Highlighting für Python Strukturä sowiä repr Text machä. Went e Collection (wiä zum Bispiil dict oder list) loggsch wird Rich das hübsch Usgeh so dass es i de verfüägbari Platz ine passt. Do es Bispiil für e paar vo dene Funktionä. + +```python +from rich.console import Console +console = Console() + +test_data = [ + {"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "id": "1",}, + {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}, + {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": "2"}, +] + +def test_log(): + enabled = False + context = { + "foo": "bar", + } + movies = ["Deadpool", "Rise of the Skywalker"] + console.log("Hello from", console, "!") + console.log(test_data, log_locals=True) + + +test_log() +``` + +Das do obe gid di folgend Usgob: + +![Log](https://github.com/willmcgugan/rich/raw/master/imgs/log.png) + +Beachte s Argument `log_locals` wo innere Tabelle di lokalä Variable us gid zur Zitt wo d Methodä ufgruäfä worde isch. + +D log Methodä cha zum is Törminäl inne z Logge für langläbige Applikationä wie Server brucht werde isch aber au fürs Debuggä ganz e netti Hilf. + +
+
+Logging Handler + +Du chasch au d Builtin [Handler Class](https://rich.readthedocs.io/en/latest/logging.html) verwende zum d Usgob vom Python logging Module z formatiäre und iifärbe. Do es Bispiil vo de Usgob: + +![Logging](https://github.com/willmcgugan/rich/raw/master/imgs/logging.png) + +
+ +
+Emoji + +Zom e Emoji i de Konsoleusgob iizfüäge tuä de name züschet zwei Doppelpünkt. Do es Bispiil: + +```python +>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:") +😃 🧛 💩 👍 🦝 +``` + +Bitte verwend diä Funktion gschiid. + +
+ +
+Tabelle + +Rich cha flexiibäl [Tabelle](https://rich.readthedocs.io/en/latest/tables.html) mit Boxä us Unicodezeiche generiäre. Es gid e Viilzahl vo Formatiärigsoptionä für Ränder, Stiil, Zelleusrichtig ond so witter. + +![table movie](https://github.com/willmcgugan/rich/raw/master/imgs/table_movie.gif) + +D Animation obe isch mit [table_movie.py](https://github.com/willmcgugan/rich/blob/master/examples/table_movie.py) us em Bispiil Ordner erstellt worde. + +Do es eifachs Tabelle Bispiil: + +```python +from rich.console import Console +from rich.table import Table + +console = Console() + +table = Table(show_header=True, header_style="bold magenta") +table.add_column("Date", style="dim", width=12) +table.add_column("Title") +table.add_column("Production Budget", justify="right") +table.add_column("Box Office", justify="right") +table.add_row( + "Dev 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118" +) +table.add_row( + "May 25, 2018", + "[red]Solo[/red]: A Star Wars Story", + "$275,000,000", + "$393,151,347", +) +table.add_row( + "Dec 15, 2017", + "Star Wars Ep. VIII: The Last Jedi", + "$262,000,000", + "[bold]$1,332,539,889[/bold]", +) + +console.print(table) +``` + +Das gid di folgend Usgob: + +![table](https://github.com/willmcgugan/rich/raw/master/imgs/table.png) + +Beacht das d Konsole Markup glich wie bi `print()` ond `log()` generiärt wird. Ond zwor cha alles wo vo Rich generiert werde cha au im Chopf / Zille iigfüägt werde (sogar anderi Tabellene). + +D Klass `Table` isch gschiid gnuäg yum d Spaltebreite am verfüägbare Platz im Törminäl aazpasse und de Text gegäbenefalls umzbreche. Do isch s gliche Bispiil mit em Törminäl chlinner als d Tabelle vo obe: + +![table2](https://github.com/willmcgugan/rich/raw/master/imgs/table2.png) + +
+ +
+Progress Bars + +Rich cha meereri flackerfreii [Progress](https://rich.readthedocs.io/en/latest/progress.html) Bars darstelle zum langläbigi Tasks verfolgä. + +Zur eifache Benutzig irgend e Sequenz id `track` Funktion ine packe und über s Resultat iteriäre. Do es Bispiil: + +```python +from rich.progress import track + +for step in track(range(100)): + do_step(step) +``` + +Es isch nöd vill schwiriger zum mehräri Progress Bars hinzuä zfüäge. Do es Bispiil us de Doku: + +![progress](https://github.com/willmcgugan/rich/raw/master/imgs/progress.gif) + +D Spaltä cha so konfiguriärt werde das alli gwünschte Details aazeigt werded. D Built-in Spalte beinhaltät Prozentsatz, Dateigrössi, Dateigschwindikeit ond öbrigi Zitt. Do isch e andos Bispiil wo en laufände Download zeigt: + +![progress](https://github.com/willmcgugan/rich/raw/master/imgs/downloader.gif) + +Zums selber usprobiäre lueg [examples/downloader.py](https://github.com/willmcgugan/rich/blob/master/examples/downloader.py) a, wo cha glichzittig mehräri URLs abelade und de Fortschritt aazeige. + +
+ +
+Status + +För Situatione wos schwär isch zum de Fortschritt z berechne, chasch d [status](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) Methode verwende wo en 'spinner' animiärt und e Nochricht darstellt. D Animation haltet di nöd ab d Konsole witter normal z bruche. Do es Bispiil: + +```python +from time import sleep +from rich.console import Console + +console = Console() +tasks = [f"task {n}" for n in range(1, 11)] + +with console.status("[bold green]Working on tasks...") as status: + while tasks: + task = tasks.pop(0) + sleep(1) + console.log(f"{task} complete") +``` + +Das gid di folgendi Usgob im Törminäl. + +![status](https://github.com/willmcgugan/rich/raw/master/imgs/status.gif) + +D Spinner Animatione sind vo [cli-spinners](https://www.npmjs.com/package/cli-spinners) usglehnt. Du chasch en speziifischä Spinner mit em `spinner` Parameter uswähle. Start de folgend Befehl zom die verfüägbare Wert z gsiä: + +``` +python -m rich.spinner +``` + +De Befehlt obe generiärt di folgändi Usgob im Törminäl: + +![spinners](https://github.com/willmcgugan/rich/raw/master/imgs/spinners.gif) + +
+ +
+Tree + +Rich cha en [tree](https://rich.readthedocs.io/en/latest/tree.html) mit Hilfsliniä generiäre. En Tree isch ideal zom darstelle vo Dateistruktuure oder anderi hirarchischi Date. + +S Label vom Tree cha en eifache Text or alles andere wo Rich cha rendere. Start das Folgendi für e Demonstation: + +``` +python -m rich.tree +``` + +Das generiärt di folgend Usgob: + +![markdown](https://github.com/willmcgugan/rich/raw/master/imgs/tree.png) + +Lueg s Bispiil Script [tree.py](https://github.com/willmcgugan/rich/blob/master/examples/tree.py) für e Darstellig vo irgend eim Ordner als Tree, glich wie de Linux Befehl `tree`. + +
+ +
+Columns + +Rich can render content in neat [columns](https://rich.readthedocs.io/en/latest/columns.html) with equal or optimal width. Here's a very basic clone of the (MacOS / Linux) `ls` command which displays a directory listing in columns: + +```python +import os +import sys + +from rich import print +from rich.columns import Columns + +directory = os.listdir(sys.argv[1]) +print(Columns(directory)) +``` + +De folgend Screenshot isch d Usgob vom [columns example](https://github.com/willmcgugan/rich/blob/master/examples/columns.py) Bispiil, wo Date vonnere API hollt ond in Colums darstellt: + +![columns](https://github.com/willmcgugan/rich/raw/master/imgs/columns.png) + +
+ +
+Markdown + +Rich cha [markdown](https://rich.readthedocs.io/en/latest/markdown.html) übersetze ond leistet vernünftigi Ärbät bim formatiärige is Törminäl z übersetze. + +Zum Markdonw z übersetze importier d Klass `Markdown` und instanzier es mitem Markdown Text. Nocher gid mos uf de Konsolä us. Do es Bispiil: + +```python +from rich.console import Console +from rich.markdown import Markdown + +console = Console() +with open("README.md") as readme: + markdown = Markdown(readme.read()) +console.print(markdown) +``` + +Das wird d Usgob ungefär wie s Folgende geh: + +![markdown](https://github.com/willmcgugan/rich/raw/master/imgs/markdown.png) + +
+ +
+Syntax Highlighting + +Rich brucht d [pygments](https://pygments.org/) Library für d [Syntax Highlighting](https://rich.readthedocs.io/en/latest/syntax.html). S Bruche isch ähnloch zum Markdown übersetze; instanziär e `Syntax` Objekt ond gibs uf de Konsolä us. Do es Bispiil: + +```python +from rich.console import Console +from rich.syntax import Syntax + +my_code = ''' +def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]: + """Iterate and generate a tuple with a flag for first and last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + first = True + for value in iter_values: + yield first, False, previous_value + first = False + previous_value = value + yield first, True, previous_value +''' +syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True) +console = Console() +console.print(syntax) +``` + +Das wird d Usgob ungefär wie s Folgende geh: + +![syntax](https://github.com/willmcgugan/rich/raw/master/imgs/syntax.png) + +
+ +
+Tracebacks + +Rich cha [wunderschöni Tracebacks](https://rich.readthedocs.io/en/latest/traceback.html) generiäre wo eifach zum läse sind und meh Code als de standart Python Traceback darstellt. Du chasch Rich als default Traceback Handler setzä ond alli nöd abfangene Exceptions werded mit Rich dargstellt. + +So gsiets ungefär ufemen OSX (ähnloch uf Linux) us: + +![traceback](https://github.com/willmcgugan/rich/raw/master/imgs/traceback.png) + +
+ +Alli Rich Renderables bruched s [Console Protokoll](https://rich.readthedocs.io/en/latest/protocol.html), wo mo au für d eige entwicklig vo Rich Inhalt cha bruche. + +# Rich für Ondernemä + +Verfüägbar als Tidelift Abo. + +De Betreue vo Rich ond tuusigi anderi Päkli schaffed mit Tidelift zum komerziälle Support und Wartig für Open Source Päkli wo du zum Baue vo dinnere Applikation bruchsch. Spar Zit, reduziär s Risiko ond verbessere d Code Health mit em bezahle vo de Wartig für gnau die Päkli wo mo brucht. [Lärn meh.](https://tidelift.com/subscription/pkg/pypi-rich?utm_source=pypi-rich&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +# Projekt wo Rich bruched + +Do es paar Projekt wo Rich verwended: + +- [BrancoLab/BrainRender](https://github.com/BrancoLab/BrainRender) + a python package for the visualization of three dimensional neuro-anatomical data +- [Ciphey/Ciphey](https://github.com/Ciphey/Ciphey) + Automated decryption tool +- [emeryberger/scalene](https://github.com/emeryberger/scalene) + a high-performance, high-precision CPU and memory profiler for Python +- [hedythedev/StarCli](https://github.com/hedythedev/starcli) + Browse GitHub trending projects from your command line +- [intel/cve-bin-tool](https://github.com/intel/cve-bin-tool) + This tool scans for a number of common, vulnerable components (openssl, libpng, libxml2, expat and a few others) to let you know if your system includes common libraries with known vulnerabilities. +- [nf-core/tools](https://github.com/nf-core/tools) + Python package with helper tools for the nf-core community. +- [cansarigol/pdbr](https://github.com/cansarigol/pdbr) + pdb + Rich library for enhanced debugging +- [plant99/felicette](https://github.com/plant99/felicette) + Satellite imagery for dummies. +- [seleniumbase/SeleniumBase](https://github.com/seleniumbase/SeleniumBase) + Automate & test 10x faster with Selenium & pytest. Batteries included. +- [smacke/ffsubsync](https://github.com/smacke/ffsubsync) + Automagically synchronize subtitles with video. +- [tryolabs/norfair](https://github.com/tryolabs/norfair) + Lightweight Python library for adding real-time 2D object tracking to any detector. +- [ansible/ansible-lint](https://github.com/ansible/ansible-lint) Ansible-lint checks playbooks for practices and behaviour that could potentially be improved +- [ansible-community/molecule](https://github.com/ansible-community/molecule) Ansible Molecule testing framework +- +[Many more](https://github.com/willmcgugan/rich/network/dependents)! + + diff --git a/README.de.md b/README.de.md index 6c6b1af6c..68ed8390a 100644 --- a/README.de.md +++ b/README.de.md @@ -1,3 +1,4 @@ +[![Downloads](https://pepy.tech/badge/rich/month)](https://pepy.tech/project/rich) [![PyPI version](https://badge.fury.io/py/rich.svg)](https://badge.fury.io/py/rich) [![codecov](https://codecov.io/gh/willmcgugan/rich/branch/master/graph/badge.svg)](https://codecov.io/gh/willmcgugan/rich) [![Rich blog](https://img.shields.io/badge/blog-rich%20news-yellowgreen)](https://www.willmcgugan.com/tag/rich/) @@ -5,6 +6,9 @@ ![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg) +[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) • [Français readme](https://github.com/willmcgugan/rich/blob/master/README.fr.md) • [Schwizerdütsch readme](https://github.com/willmcgugan/rich/blob/master/README.de-ch.md) • [हिन्दी readme](https://github.com/willmcgugan/rich/blob/master/README.hi.md) + • [Português brasileiro readme](https://github.com/willmcgugan/rich/blob/master/README.pt-br.md) + Rich ist eine Python-Bibliothek für _rich_ Text und schöne Formatierung im Terminal. Die [Rich API](https://rich.readthedocs.io/en/latest/) erleichtert das Hinzufügen von Farbe und Stil zur Terminalausgabe. Rich kann auch schöne Tabellen, Fortschrittsbalken, Markdowns, durch Syntax hervorgehobenen Quellcode, Tracebacks und mehr sofort rendern. diff --git a/README.es.md b/README.es.md index d5f668a55..f01d14de3 100644 --- a/README.es.md +++ b/README.es.md @@ -6,9 +6,10 @@ ![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg) -[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) +[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) • [Français readme](https://github.com/willmcgugan/rich/blob/master/README.fr.md) • [Schwizerdütsch readme](https://github.com/willmcgugan/rich/blob/master/README.de-ch.md) • [हिन्दी readme](https://github.com/willmcgugan/rich/blob/master/README.hi.md) Rich es un paquete de Python para texto _enriquecido_ y un hermoso formato en la terminal. + • [Português brasileiro readme](https://github.com/willmcgugan/rich/blob/master/README.pt-br.md) La [API Rich](https://rich.readthedocs.io/en/latest/) facilita la adición de color y estilo a la salida del terminal. Rich también puede representar tablas bonitas, barras de progreso, markdown, código fuente resaltado por sintaxis, trazas y más — listo para usar. diff --git a/README.fr.md b/README.fr.md new file mode 100644 index 000000000..92d761dfa --- /dev/null +++ b/README.fr.md @@ -0,0 +1,435 @@ +[![Downloads](https://pepy.tech/badge/rich/month)](https://pepy.tech/project/rich) +[![PyPI version](https://badge.fury.io/py/rich.svg)](https://badge.fury.io/py/rich) +[![codecov](https://codecov.io/gh/willmcgugan/rich/branch/master/graph/badge.svg)](https://codecov.io/gh/willmcgugan/rich) +[![Rich blog](https://img.shields.io/badge/blog-rich%20news-yellowgreen)](https://www.willmcgugan.com/tag/rich/) +[![Twitter Follow](https://img.shields.io/twitter/follow/willmcgugan.svg?style=social)](https://twitter.com/willmcgugan) + +![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg) + +[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) • [Français readme](https://github.com/willmcgugan/rich/blob/master/README.fr.md) • [Schwizerdütsch readme](https://github.com/willmcgugan/rich/blob/master/README.de-ch.md) • [हिन्दी readme](https://github.com/willmcgugan/rich/blob/master/README.hi.md) + • [Português brasileiro readme](https://github.com/willmcgugan/rich/blob/master/README.pt-br.md) + +Rich est une bibliothèque Python pour le _rich_ texte et la mise en forme dans le terminal. + +L'[API Rich](https://rich.readthedocs.io/en/latest/) permet d'ajouter facilement de la couleur et du style sur la sortie du terminal. Rich peut également rendre de jolis tableaux, des barres de progression, du markdown, du code source avec de la coloration syntaxique, des traçeurs d'erreurs et bien d'autres choses encore, et ce dès le départ. + +![Features](https://github.com/willmcgugan/rich/raw/master/imgs/features.png) + +Pour une introduction vidéo à Rich, voir [camelcode.io](https://calmcode.io/rich/introduction.html) par [@ fishnets88](https://twitter.com/fishnets88) + +Voyez ce que [les gens disent de Rich](https://www.willmcgugan.com/blog/pages/post/rich-tweets/) + +## Compatibilité + +Rich fonctionne avec Linux, OSX et Windows. True color / emoji fonctionne avec le nouveau Terminal Windows, le terminal classique est limité à 16 couleurs. Rich nécessite Python 3.6.1 ou plus. + +Rich fonctionne avec les notebooks Jupyter sans configuration supplémentaire. + +## Installation + +Installez avec `pip` ou votre gestionnaire de paquets Pypi préféré. + +``` +pip install rich +``` + +Exécutez ce qui suit pour tester la sortie de Rich sur votre terminal : + +``` +python -m rich +``` + +## Rich Print + +Pour ajouter sans effort une sortie Rich à votre application, vous pouvez importer la méthode [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start), qui a la même signature que la fonction Python intégrée. Essayez ceci : + +```python +from rich import print + +print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals()) +``` + +![Hello World](https://github.com/willmcgugan/rich/raw/master/imgs/print.png) + +## Rich REPL + +Rich peut être installé dans le REPL de Python, de sorte que toutes les structures de données seront joliment affichées et mises en évidence. + +```python +>>> from rich import pretty +>>> pretty.install() +``` + +![REPL](https://github.com/willmcgugan/rich/raw/master/imgs/repl.png) + +## Utilisation de Console + +Pour mieux contrôler le contenu rich du terminal, importez et construisez un objet [Console](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console) + +```python +from rich.console import Console + +console = Console() +``` + +L'objet Console possède une méthode `print` dont l'interface est intentionnellement similaire à celle de la fonction `print` native. Voici un exemple d'utilisation : + +```python +console.print("Hello", "World!") +``` + +Comme vous pouvez vous y attendre, cela va afficher "Hello World !" sur le terminal. Notez que, contrairement à la fonction d'affichage intégrée, Rich mettra votre texte en forme pour qu'il tienne dans la largeur du terminal. + +Il y a plusieurs façons d'ajouter de la couleur et du style à votre sortie. Vous pouvez définir un style pour l'ensemble de la sortie en ajoutant un argument de mot-clé style. Voici un exemple : + +```python +console.print("Hello", "World!", style="bold red") +``` + +La sortie sera quelque chose comme ce qui suit : + +![Hello World](https://github.com/willmcgugan/rich/raw/master/imgs/hello_world.png) + +C'est très bien pour styliser une ligne de texte à la fois. Pour un style plus fin, Rich rend un balisage spécial dont la syntaxe est similaire à celle du [bbcode](https://en.wikipedia.org/wiki/BBCode). Voici un exemple : + +```python +console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].") +``` + +![Console Markup](https://github.com/willmcgugan/rich/raw/master/imgs/where_there_is_a_will.png) + +Vous pouvez utiliser un objet Console pour générer une sortie sophistiquée avec un effort minimal. Consultez la documentation de l'[API Console](https://rich.readthedocs.io/en/latest/console.html) pour plus de détails. + +## Rich Inspect + +Rich possède une fonction [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) qui peut produire un rapport sur n'importe quel objet Python, comme une classe, une instance ou une fonction intégrée. + +```python +>>> my_list = ["foo", "bar"] +>>> from rich import inspect +>>> inspect(my_list, methods=True) +``` + +![Log](https://github.com/willmcgugan/rich/raw/master/imgs/inspect.png) + +Consultez la [documentation d'inspect](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect) pour plus de détails. + +## Bibliothèque Rich +Rich contient un certain nombre _d'éléments de rendu_ intégrés que vous pouvez utiliser pour créer une sortie élégante dans votre CLI et vous aider à déboguer votre code. + +Cliquez sur les rubriques suivantes pour plus de détails : + +
+Log + +L'objet Console a une méthode `log()` qui a une interface similaire à `print()`, mais qui rend aussi une colonne pour l'heure actuelle, le fichier et la ligne qui ont fait l'appel. Par défaut, Rich fera la coloration syntaxique des structures Python et des chaînes repr. Si vous enregistrez une collection (i.e. un dict ou une liste) Rich affichera la collection de façon à ce qu'elle tienne dans l'espace disponible. Voici un exemple de certaines de ces fonctionnalités. + +```python +from rich.console import Console +console = Console() + +test_data = [ + {"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "id": "1",}, + {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}, + {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": "2"}, +] + +def test_log(): + enabled = False + context = { + "foo": "bar", + } + movies = ["Deadpool", "Rise of the Skywalker"] + console.log("Hello from", console, "!") + console.log(test_data, log_locals=True) + + +test_log() +``` + +L'opération ci-dessus produit le résultat suivant : + +![Log](https://github.com/willmcgugan/rich/raw/master/imgs/log.png) + +Notez l'argument `log_locals`, qui produit un tableau contenant les variables locales où la méthode log a été appelée. + +La méthode log peut être utilisée pour la journalisation vers le terminal pour les applications qui tournent longtemps, comme les serveurs, mais c'est aussi une très bonne aide au débogage. +
+ +
+Journalisation + +Vous pouvez également utiliser la classe intégrée [Handler](https://rich.readthedocs.io/en/latest/logging.html) pour formater et coloriser les sorties du module de journalisation de Python. Voici un exemple de sortie : + +![Logging](https://github.com/willmcgugan/rich/raw/master/imgs/logging.png) +
+ +
+Emoji + +Pour insérer un emoji dans la sortie de la console, placez le nom entre deux points. Voici un exemple : + +```python +>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:") +😃 🧛 💩 👍 🦝 +``` + +Veuillez utiliser cette fonction à bon escient. +
+ +
+Tableaux + +Rich peut rendre des [tableaux](https://rich.readthedocs.io/en/latest/tables.html) flexibles avec des caractères de boîte unicode. Il existe une grande variété d'options de formatage pour les bordures, les styles, l'alignement des cellules, etc. + +![table movie](https://github.com/willmcgugan/rich/raw/master/imgs/table_movie.gif) + +L'animation ci-dessus a été générée avec [table_movie.py](https://github.com/willmcgugan/rich/blob/master/examples/table_movie.py) dans le répertoire des exemples. + +Voici un exemple de tableau plus simple : + +```python +from rich.console import Console +from rich.table import Table + +console = Console() + +table = Table(show_header=True, header_style="bold magenta") +table.add_column("Date", style="dim", width=12) +table.add_column("Title") +table.add_column("Production Budget", justify="right") +table.add_column("Box Office", justify="right") +table.add_row( + "Dev 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118" +) +table.add_row( + "May 25, 2018", + "[red]Solo[/red]: A Star Wars Story", + "$275,000,000", + "$393,151,347", +) +table.add_row( + "Dec 15, 2017", + "Star Wars Ep. VIII: The Last Jedi", + "$262,000,000", + "[bold]$1,332,539,889[/bold]", +) + +console.print(table) +``` + +Cela produit le résultat suivant : + +![table](https://github.com/willmcgugan/rich/raw/master/imgs/table.png) + +Notez que les balises de la console sont rendues de la même manière que `print()` et `log()`. En fait, tout ce qui peut être rendu par Rich peut être inclus dans les en-têtes / lignes (même d'autres tables). + +La classe `Table` est suffisamment intelligente pour redimensionner les colonnes en fonction de la largeur disponible du terminal, en enveloppant le texte si nécessaire. Voici le même exemple, avec un terminal plus petit que le tableau ci-dessus : + +![table2](https://github.com/willmcgugan/rich/raw/master/imgs/table2.png) +
+ +
+Barres de progression + +Rich peut afficher plusieurs [barres de progression](https://rich.readthedocs.io/en/latest/progress.html) sans scintillement pour suivre les tâches de longue haleine. + +Pour une utilisation basique, bouclez sur n'importe quelle séquence dans la fonction `track` et itérez sur le résultat. Voici un exemple : + +```python +from rich.progress import track + +for step in track(range(100)): + do_step(step) +``` + +Il n'est pas beaucoup plus difficile d'ajouter plusieurs barres de progression. Voici un exemple tiré de la documentation : + +![progress](https://github.com/willmcgugan/rich/raw/master/imgs/progress.gif) + +Les colonnes peuvent être configurées pour afficher tous les détails que vous souhaitez. Les colonnes intégrées comprennent le pourcentage d'achèvement, la taille du fichier, la vitesse du fichier et le temps restant. Voici un autre exemple montrant un téléchargement en cours : + +![progress](https://github.com/willmcgugan/rich/raw/master/imgs/downloader.gif) + +Pour l'essayer vous-même, voyez [examples/downloader.py](https://github.com/willmcgugan/rich/blob/master/examples/downloader.py) qui peut télécharger plusieurs URL simultanément tout en affichant la progression. + +
+ +
+Statut + +Pour les situations où il est difficile de calculer la progression, vous pouvez utiliser la méthode [status](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) qui affichera une animation et un message de type "spinner". L'animation ne vous empêchera pas d'utiliser la console normalement. Voici un exemple : + +```python +from time import sleep +from rich.console import Console + +console = Console() +tasks = [f"task {n}" for n in range(1, 11)] + +with console.status("[bold green]Working on tasks...") as status: + while tasks: + task = tasks.pop(0) + sleep(1) + console.log(f"{task} complete") +``` + +Cela génère la sortie suivante dans le terminal. + +![status](https://github.com/willmcgugan/rich/raw/master/imgs/status.gif) + +Les animations des toupies ont été empruntées à [cli-spinners](https://www.npmjs.com/package/cli-spinners). Vous pouvez sélectionner un spinner en spécifiant le paramètre `spinner`. Exécutez la commande suivante pour voir les valeurs disponibles : + +``` +python -m rich.spinner +``` + +La commande ci-dessus génère la sortie suivante dans le terminal : + +![spinners](https://github.com/willmcgugan/rich/raw/master/imgs/spinners.gif) +
+ +
+Arborescence + +Rich peut affiché une [arborescence](https://rich.readthedocs.io/en/latest/tree.html) avec des lignes de repère. Une arborescence est idéale pour afficher une structure de fichiers, ou toute autre donnée hiérarchique. + +Les étiquettes de cette arborescence peuvent être du texte simple ou tout autre élément que Rich peut rendre. Exécutez ce qui suit pour une démonstration : + +``` +python -m rich.tree +``` + +La commande ci-dessus génère la sortie suivante dans le terminal : + +![markdown](https://github.com/willmcgugan/rich/raw/master/imgs/tree.png) + +Voir l'exemple [tree.py](https://github.com/willmcgugan/rich/blob/master/examples/tree.py) pour un script qui affiche une vue arborescente de n'importe quel répertoire, similaire à la commande linux `tree`. + +
+ +
+Colonnes + +Rich peut rendre le contenu en [colonnes](https://rich.readthedocs.io/en/latest/columns.html) avec une largeur égale ou optimale. Voici un clone très basique de la commande `ls` (MacOS / Linux) qui affiche une liste de répertoires en colonnes : + +```python +import os +import sys + +from rich import print +from rich.columns import Columns + +directory = os.listdir(sys.argv[1]) +print(Columns(directory)) +``` + +La capture d'écran suivante est le résultat de [columns example](https://github.com/willmcgugan/rich/blob/master/examples/columns.py) qui affiche les données extraites d'une API en colonnes : + +![colonne](https://github.com/willmcgugan/rich/raw/master/imgs/columns.png) + +
+ +
+Markdown + +Rich peut rendre le [markdown](https://rich.readthedocs.io/en/latest/markdown.html) et fait un travail raisonnable pour traduire le formatage dans le terminal. + +Pour rendre du markdown, importez la classe `Markdown` et construisez-la avec une chaîne contenant du code markdown. Ensuite, affichez-la dans la console. Voici un exemple : + +```python +from rich.console import Console +from rich.markdown import Markdown + +console = Console() +with open("README.md") as readme: + markdown = Markdown(readme.read()) +console.print(markdown) +``` + +Cela produira un résultat semblable à ce qui suit : + +![markdown](https://github.com/willmcgugan/rich/raw/master/imgs/markdown.png) + +
+ +
+Mise en couleur de la syntaxe + +Rich utilise la bibliothèque [pygments](https://pygments.org/) pour implémenter la [coloration syntaxique](https://rich.readthedocs.io/en/latest/syntax.html). L'utilisation est similaire au rendu de markdown ; construire un objet `Syntax` et afficher celui-ci sur la console. Voici un exemple : + +```python +from rich.console import Console +from rich.syntax import Syntax + +my_code = ''' +def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]: + """Iterate and generate a tuple with a flag for first and last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + first = True + for value in iter_values: + yield first, False, previous_value + first = False + previous_value = value + yield first, True, previous_value +''' +syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True) +console = Console() +console.print(syntax) +``` + +Cela produira le résultat suivant : + +![syntax](https://github.com/willmcgugan/rich/raw/master/imgs/syntax.png) +
+ +
+Tracebacks + +Rich peut rendre des [traçages d'erreurs](https://rich.readthedocs.io/en/latest/traceback.html) plus faciles à lire et montrent plus de code que les traçages d'erreurs standard de Python. Vous pouvez définir Rich comme le gestionnaire d'erreurs par défaut afin que toutes les exceptions non capturées soient rendues par Rich. + +Voici à quoi cela ressemble sous OSX (similaire sous Linux) : + +![traceback](https://github.com/willmcgugan/rich/raw/master/imgs/traceback.png) + +
+ +Tous les éléments de rendu utilisent le [Console Protocol](https://rich.readthedocs.io/en/latest/protocol.html), que vous pouvez également utiliser pour mettre en œuvre votre propre contenu Rich. + +# Rich pour les entreprises + +Disponible dans le cadre de l'abonnement Tidelift. + +Les mainteneurs de Rich et de milliers d'autres paquets collaborent avec Tidelift pour fournir un support et une maintenance commerciale pour les paquets open source que vous utilisez pour construire vos applications. Gagnez du temps, réduisez les risques et améliorez la qualité du code, tout en payant les mainteneurs des paquets que vous utilisez. [En savoir plus](https://tidelift.com/subscription/pkg/pypi-rich?utm_source=pypi-rich&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +# Projets utilisant Rich + +- [BrancoLab/BrainRender](https://github.com/BrancoLab/BrainRender) + un package python pour la visualisation de données neuro-anatomiques tridimensionnelles +- [Ciphey/Ciphey](https://github.com/Ciphey/Ciphey) + Outil de déchiffrage automatisé +- [emeryberger/scalene](https://github.com/emeryberger/scalene) + un profileur de CPU et de mémoire haute performance et haute précision pour Python +- [hedythedev/StarCli](https://github.com/hedythedev/starcli) + Parcourir les projets tendances de GitHub à partir de votre ligne de commande +- [intel/cve-bin-tool](https://github.com/intel/cve-bin-tool) + Cet outil recherche un certain nombre de composants courants et vulnérables (openssl, libpng, libxml2, expat et quelques autres) pour vous indiquer si votre système comprend des bibliothèques présentant des vulnérabilités connues. +- [nf-core/tools](https://github.com/nf-core/tools) + Paquet Python contenant des outils d'aide pour la communauté nf-core. +- [cansarigol/pdbr](https://github.com/cansarigol/pdbr) + pdb + bibliothèque Rich pour un débogage amélioré +- [plant99/felicette](https://github.com/plant99/felicette) + L'imagerie satellite pour les nuls. +- [seleniumbase/SeleniumBase](https://github.com/seleniumbase/SeleniumBase) + Automatisez et testez 10 fois plus vite avec Selenium et pytest. Piles incluses. +- [smacke/ffsubsync](https://github.com/smacke/ffsubsync) + Synchronisation automatique des sous-titres avec la vidéo. +- [tryolabs/norfair](https://github.com/tryolabs/norfair) + Bibliothèque Python légère pour ajouter le suivi d'objets 2D en temps réel à n'importe quel détecteur. +- [ansible/ansible-lint](https://github.com/ansible/ansible-lint) Ansible-lint vérifie dans les playbooks les pratiques et comportements qui pourraient être améliorés. +- [ansible-community/molecule](https://github.com/ansible-community/molecule) Cadre de test Ansible Molecule. +- [Beaucoup d'autres](https://github.com/willmcgugan/rich/network/dependents) ! diff --git a/README.hi.md b/README.hi.md new file mode 100644 index 000000000..3692a8287 --- /dev/null +++ b/README.hi.md @@ -0,0 +1,432 @@ +[![Downloads](https://pepy.tech/badge/rich/month)](https://pepy.tech/project/rich) +[![PyPI version](https://badge.fury.io/py/rich.svg)](https://badge.fury.io/py/rich) +[![codecov](https://codecov.io/gh/willmcgugan/rich/branch/master/graph/badge.svg)](https://codecov.io/gh/willmcgugan/rich) +[![Rich blog](https://img.shields.io/badge/blog-rich%20news-yellowgreen)](https://www.willmcgugan.com/tag/rich/) +[![Twitter Follow](https://img.shields.io/twitter/follow/willmcgugan.svg?style=social)](https://twitter.com/willmcgugan) + +![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg) + +[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) • [Français readme](https://github.com/willmcgugan/rich/blob/master/README.fr.md) • [Schwizerdütsch readme](https://github.com/willmcgugan/rich/blob/master/README.de-ch.md) • [हिन्दी readme](https://github.com/willmcgugan/rich/blob/master/README.hi.md) + • [Português brasileiro readme](https://github.com/willmcgugan/rich/blob/master/README.pt-br.md) + +Rich टर्मिनल में _समृद्ध_ पाठ और सुंदर स्वरूपण के लिए एक Python संग्रह है। + + +[Rich API](https://rich.readthedocs.io/en/latest/) टर्मिनल उत्पादन में रंग और शैली डालना आसान बनाता है। Rich सुंदर सारणियाँ, प्रगति सूचक डंडे, markdown, रचनाक्रम चिन्हांकित स्त्रोत कोड, ट्रेसबैक आदि प्रस्तुत कर सकता है - बिना कुछ बदले। + +![Features](https://github.com/willmcgugan/rich/raw/master/imgs/features.png) + +Rich के वीडियो परिचय के लिए देखें [@fishnets88](https://twitter.com/fishnets88) द्वारा बनाई गई [calmcode.io](https://calmcode.io/rich/introduction.html)। + + +देखें [लोग रिच के बारे में क्या कह रहे हैं](https://www.willmcgugan.com/blog/pages/post/rich-tweets/)। + +## अनुकूलता + +Rich Linux, OSX, और Windows के साथ चल सकता है। सच्चा रंग/इमोजी नए Windows टर्मिनल के साथ काम करता है, पुराना टर्मिनल १६ रंगों तक ही सीमित है। Rich के लिए Python ३.६.१ या बाद का होना आवश्यक है। + +Rich बिना किसी अतिरिक्त विन्यास के [Jupyter नोटबुक](https://jupyter.org/) के साथ काम करता है। + +## स्थापना करना + +`pip` या अपने पसंदीदा PyPI संकुल प्रबंधक (package manager) के द्वारा आप इसे स्थापित कर सकते हैं। + +``` +pip install rich +``` + +आपके टर्मिनल पर Rich उत्पादन का परीक्षण करने के लिए यह चलाएं: +``` +python -m rich +``` + +## Rich Print + +अपने अनुप्रयोग में सरलता से समृद्ध उत्पादन जोड़ने के लिए, आप [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start) क्रिया को आयात कर सकते हैं, जिसका हस्ताक्षर अंतर्निहित Python क्रिया के समान है। यह चलाने की कोशिश करें: + +```python +from rich import print + +print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals()) +``` + +![Hello World](https://github.com/willmcgugan/rich/raw/master/imgs/print.png) + +## Rich REPL + +Rich को Python REPL में स्थापित किया जा सकता है, ताकि कोई भी डेटा संरचनाएं सुंदरता से छपे तथा चिह्नांकित हों। +```python +>>> from rich import pretty +>>> pretty.install() +``` + +![REPL](https://github.com/willmcgugan/rich/raw/master/imgs/repl.png) + +## कॉनसोल (Console) का इस्तेमाल करना + +समृद्ध टर्मिनल वस्तुओं पर अधिक नियंत्रण के लिए, आयात और निर्मित करें एक [Console](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console) वस्तु को। + +```python +from rich.console import Console + +console = Console() +``` + +Console वस्तु के पास एक `print` क्रिया है जिसका अंतरापृष्ठ जानबूझ कर अंतर्निहित `print` क्रिया के सामान है। इसके इस्तेमाल का एक उदाहरण : +```python +console.print("Hello", "World!") +``` + + +जैसा आप उम्मीद कर रहे होंगे, यह टर्मिनल पर `"Hello World!"` छाप देगा। ध्यान दें की अंतर्निहित `print` क्रिया के भिन्न, Rich आपके पाठ को "वर्ड-रैप" कर देगा ताकि वह टर्मिनल की चौड़ाई में फस सके। + +अपने उत्पादन में रंग और शैली डालने के लिए एक से अधिक तरीके हैं। `style` कीवर्ड तर्क जोड़कर आप सम्पूर्ण उत्पादन के लिए शैली निर्धारित कर सकते हैं। इसका एक उदाहरण: +```python +console.print("Hello", "World!", style="bold red") +``` + +उत्पादन कुछ इस प्रकार का होगा: +![Hello World](https://github.com/willmcgugan/rich/raw/master/imgs/hello_world.png) + + +ये एक बारी में एक पंक्ति का शैलीकरण करने के लिए तो ठीक है। अधिक बारीकी से शैलीकरण करने के लिए, Rich एक विशेष मार्कअप को प्रदर्शित करता है जो रचनाक्रम में [bbcode](https://en.wikipedia.org/wiki/BBCode) से मिलता-जुलता है। इसका एक उदाहरण: + +```python +console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].") +``` + +![Console Markup](https://github.com/willmcgugan/rich/raw/master/imgs/where_there_is_a_will.png) + +कम-से-कम मेहनत में परिष्कृत उत्पादन उत्पन्न करने के लिए आप एक Console वस्तु का उपयोग कर सकते हैं। अधिक जानकारी के लिए आप [Console API](https://rich.readthedocs.io/en/latest/console.html) का प्रलेख पढ़ सकते हैं। + +## Rich Inspect + +Rich में एक [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) फलन उपलब्ध है जो किसी भी Python वस्तु, जैसे की क्लास, इन्स्टैन्स या अंतर्निहित पर प्रतिवेदन उत्पादित कर सकता है। +```python +>>> my_list = ["foo", "bar"] +>>> from rich import inspect +>>> inspect(my_list, methods=True) +``` + +![Log](https://github.com/willmcgugan/rich/raw/master/imgs/inspect.png) + +अधिक जानकारी के लिए [inspect का प्रलेखन](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect) पढ़ें। + +# Rich संग्रह + +Rich में कई अंतर्निहित _प्रतिपाद्य_ मौजूद हैं जिनका इस्तेमाल करके आप अपने CLI में सुंदर उत्पादन उत्पन्न कर सकते हैं तथा अपने कोड का दोषमार्जन (डीबग) करने में सहायता प सकते हैं। + + +जानकारी के लिए निम्न शीर्षकों पर क्लिक करें: + +
+लॉग (Log) + +Console वस्तु के पास एक `log()` फलन होता है जिसका अंतरापृष्ठ `print()` से मिलता है, पर साथ में वर्तमान समय और आवाहन करने वाली पंक्ति के लिए एक खाना प्रस्तुत करता है। व्यक्तिक्रम तौर पर Rich Python संरचनाएं एवं repr मालाओं (स्ट्रिंगों) पर रचनाक्रम चिह्नांकन करेगा। यदि आप एक संग्रह (यानि एक डिक्शनेरी या एक सूची) को लॉग करते हैं तो Rich उसे सुंदरता से छापेगा ताकि वह उपलब्ध जगह में फस सके। इनमें से कुछ विशेषताओं का उदहरण प्रस्तुत है: + +```python +from rich.console import Console +console = Console() + +test_data = [ + {"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "id": "1",}, + {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}, + {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": "2"}, +] + +def test_log(): + enabled = False + context = { + "foo": "bar", + } + movies = ["Deadpool", "Rise of the Skywalker"] + console.log("Hello from", console, "!") + console.log(test_data, log_locals=True) + + +test_log() +``` + +उपर्युक्त कोड से निम्न उत्पादन उत्पन्न होता है: + +![Log](https://github.com/willmcgugan/rich/raw/master/imgs/log.png) + +ध्यान दें `log_levels` तर्क की तरफ, जो एक सारणी उत्पादित करता है जिसमे लॉग फलन के आवाहन के स्थान के स्थानिये चर युक्त हैं। + +लॉग फलन का इस्तेमाल परिसेवकों (सर्वर) जैसे लंबे समय के लिये चलने वाले अनुप्रयोगों के लिए टर्मिनल पर प्रचालेखन के लिए किया जा सकता है, पर यह एक बहुत अच्छा दोषमार्जन सहायक भी है। + +
+
+प्रचालेखन संचालक + +Python के `logging` मापांक से आए हुए उत्पादन का संरूपण एवं रंगीकरण करने के लिए आप अंतर्निहित [Handler वर्ग](https://rich.readthedocs.io/en/latest/logging.html) का भी इस्तेमाल कर सकते हैं। उत्पादन का एक उपहरण प्रस्तुत है: + +![Logging](https://github.com/willmcgugan/rich/raw/master/imgs/logging.png) + +
+ +
+इमोजी + +Console उत्पादन में इमोजी डालने के लिए नाम को दो अपूर्ण विरामों (:) के बीच रखें। इसका एक उदाहरण: +```python +>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:") +😃 🧛 💩 👍 🦝 +``` + +कृपया इसका इस्तेमाल समझदारी से करें। +
+ +
+सारणियाँ + +Rich यूनिकोड डिब्बा अक्षरों की सहायता से लचीली [सारणियाँ](https://rich.readthedocs.io/en/latest/tables.html) प्रदर्शित कर सकता है। सीमाएँ, शैलियाँ, कक्ष संरेखण आदि के लिए कई सारे स्वरूपण विकल्प उपलब्ध हैं। + +![table movie](https://github.com/willmcgugan/rich/raw/master/imgs/table_movie.gif) + +उपर्युक्त अनुप्राणन examples डायरेक्टरी के [table_movie.py](https://github.com/willmcgugan/rich/blob/master/examples/table_movie.py) से बनाया गया है। + +इससे सरल संचिका का उदाहरण: +```python +from rich.console import Console +from rich.table import Table + +console = Console() + +table = Table(show_header=True, header_style="bold magenta") +table.add_column("Date", style="dim", width=12) +table.add_column("Title") +table.add_column("Production Budget", justify="right") +table.add_column("Box Office", justify="right") +table.add_row( + "Dev 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118" +) +table.add_row( + "May 25, 2018", + "[red]Solo[/red]: A Star Wars Story", + "$275,000,000", + "$393,151,347", +) +table.add_row( + "Dec 15, 2017", + "Star Wars Ep. VIII: The Last Jedi", + "$262,000,000", + "[bold]$1,332,539,889[/bold]", +) + +console.print(table) +``` + +इससे निम्नलिखित उत्पादन उत्पन्न होता है: + +![table](https://github.com/willmcgugan/rich/raw/master/imgs/table.png) + +ध्यान दें की कॉनसोल मार्कअप `print()` और `log()` की तरह ही प्रदर्शित होते हैं। वास्तव में, कोई भी वस्तु जो Rich के द्वारा प्रदर्शनीय है वह शीर्षकों / पंक्तियों (दूसरी संचिकाओं में भी) में युक्त किया जा सकता है। + +`Table` वर्ग इतनी बुद्धिमान है की वह टर्मिनल की उपलब्ध चौड़ाई में फ़साने के लिए स्तंभों का आकार बदल सकता है, आवश्यकता के अनुसार पाठ को लपेटते हुए। यह वही उदाहरण है, टर्मिनल को उपर्युक्त संचिका से छोटा रखते हुए: + +![table2](https://github.com/willmcgugan/rich/raw/master/imgs/table2.png) + +
+ +
+प्रगति सूचक डंडे + +लंबे समय तक चलने वाले कार्यों पर नज़र रखने के लिए Rich अनेक झिलमिलाहट-मुक्त [प्रगति सूचक](https://rich.readthedocs.io/en/latest/progress.html) डंडे प्रदर्शित कर सकता है। + +बुनियादी उपयोग के लिए, किसी भी क्रम को `track` फलन में लपेटें और परिणाम पर पुनरावर्तन करें। इसका एक उदाहरण: +```python +from rich.progress import track + +for step in track(range(100)): + do_step(step) +``` + +अनेक प्रगति सूचक डंडे जोड़ने इससे अधिक कठिन नहीं है। ये रहा एक उदाहरण जो प्रलेखन से उठाया गया है: +![progress](https://github.com/willmcgugan/rich/raw/master/imgs/progress.gif) + +स्तंभों का विन्यास इस प्रकार किया जा सकता है की आपकी इच्छानुसार विवरण दिखाए जाएँ। अंतर्निहित स्तंभ में प्रतिशत पूरा, संचिका आकार, संचिका गति तथा शेष समय युक्त होते हैं। ये रहा एक और उदाहरण एक चालू डाउनलोड को दर्शाते हुए। +![progress](https://github.com/willmcgugan/rich/raw/master/imgs/downloader.gif) + +इसे स्वयं आजमाने के लिए, देखें [examples/downloader.py](https://github.com/willmcgugan/rich/blob/master/examples/downloader.py) जो अनेक URL एक साथ डाउनलोड करते हुए प्रगति दर्शाता है। +
+ +
+स्थिति + +ऐसी परिस्थितियों में जहां प्रगति की गणना करना कठिन हों, आप [status](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) (स्थिति) फलन का उपयोग कर सकते हैं जो एक 'स्पिनर' अनुप्राणन और संदेश दर्शाएगा। अनुप्राणन आपको सामान्य तरीके से कॉनसोल को इस्तेमाल करने से नहीं रोकेगा। ये एक उदाहरण: +```python +from time import sleep +from rich.console import Console + +console = Console() +tasks = [f"task {n}" for n in range(1, 11)] + +with console.status("[bold green]Working on tasks...") as status: + while tasks: + task = tasks.pop(0) + sleep(1) + console.log(f"{task} complete") +``` + +इससे टर्मिनल में निम्नलिखित उत्पादन उत्पन्न होता है: +![status](https://github.com/willmcgugan/rich/raw/master/imgs/status.gif) + +स्पिनर अनुप्राणन [cli-spinners](https://www.npmjs.com/package/cli-spinners) से उधारे गए थे। आप `spinner` प्राचल को उल्लिखित करके स्पिनर चुन सकते हैं। उपलब्ध विकल्प देखने के लिए निम्नलिखित आदेश चलकर देखें: +``` +python -m rich.spinner +``` + +उपर्युक्त आदेश टर्मिनल में निम्नलिखित उत्पादन उतपन्न करता है: +![spinners](https://github.com/willmcgugan/rich/raw/master/imgs/spinners.gif) + +
+ +
+वृक्ष + +Rich मरकदर्शक रेखाओं से [tree](https://rich.readthedocs.io/en/latest/tree.html) (वृक्ष) प्रदर्शित कर सकता है। संचिता संरचना, अथवा कोई भी और पदानुक्रमित डेटा दर्शाने के लिए वृक्ष एक आदर्श विकल्प है। + +वृक्ष के नाम सरल पाठ्यांश या कुछ भी और जो Rich प्रदर्शित कर सके। इसके एक प्रदर्शन के लिए निम्नलिखित को चलाएं: +``` +python -m rich.tree +``` + +इससे निम्न उत्पादन उत्पन्न होता है: + +![markdown](https://github.com/willmcgugan/rich/raw/master/imgs/tree.png) + +देखें उदाहरण [tree.py](https://github.com/willmcgugan/rich/blob/master/examples/tree.py) एक क्रमादेश के लिए जो किसी भी डायरेक्टरी का वृक्ष दृश्य (ट्री व्यू) दर्शाएगा, लिनक्स के `tree` आदेश के समान। + +
+ +
+स्तंभ + + +Rich सामग्री को समान अथवा श्रेष्ट चौड़ाई के साथ स्पष्ट [स्तंभ](https://rich.readthedocs.io/en/latest/columns.html) प्रदर्शित कार सकता है। यही (MacOS / Linux) `ls` आदेश का बहुत बुनियादी प्रतिरूप प्रस्तुत किया गया है जो स्तंभों में डायरेक्टरी सूची को दर्शाता है। + +```python +import os +import sys + +from rich import print +from rich.columns import Columns + +directory = os.listdir(sys.argv[1]) +print(Columns(directory)) +``` + +निम्न स्क्रीनशॉट [स्तंभों के उदाहरण](https://github.com/willmcgugan/rich/blob/master/examples/columns.py) का उत्पादन है जो एक API से खींचे गए डेटा को स्तंभों में प्रदर्शित करता है: +![columns](https://github.com/willmcgugan/rich/raw/master/imgs/columns.png) + +
+ +
+Markdown + +Rich [markdown](https://rich.readthedocs.io/en/latest/markdown.html) को प्रदर्शित कार सकता है और स्वरूपण का अनुवाद टर्मिनल पर करने में उचित कार्य करता है। + + +Markdown प्रदर्शित करने के लिए आप `Markdown` वर्ग को आयात कार सकते हैं और उसे markdown कोड युक्त अक्षरमाला के साथ निर्मित कर सकते हैं। फिर उसे कॉनसोल पर छापें। एक उदाहरण प्रस्तुत है: +```python +from rich.console import Console +from rich.markdown import Markdown + +console = Console() +with open("README.md") as readme: + markdown = Markdown(readme.read()) +console.print(markdown) +``` + +इससे कुछ इस प्रकार का उत्पादन उत्पन्न होगा: + +![markdown](https://github.com/willmcgugan/rich/raw/master/imgs/markdown.png) + +
+ +
+रचनाक्रम चिह्नांकन + +Rich [रचनाक्रम चिह्नांकन](https://rich.readthedocs.io/en/latest/syntax.html) के लिए [pygments](https://pygments.org/) संग्रह का उपयोग करता है। उपयोग markdown को प्रदर्शित करने से मिलता-जुलता है; एक `Syntax` वस्तु निर्मित करें और उसे कॉनसोल पर छापें। एक उदाहरण: +```python +from rich.console import Console +from rich.syntax import Syntax + +my_code = ''' +def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]: + """Iterate and generate a tuple with a flag for first and last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + first = True + for value in iter_values: + yield first, False, previous_value + first = False + previous_value = value + yield first, True, previous_value +''' +syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True) +console = Console() +console.print(syntax) +``` + +This will produce the following output: +इससे निम्न उत्पादन उत्पन्न होता है: + +![syntax](https://github.com/willmcgugan/rich/raw/master/imgs/syntax.png) + +
+ +
+ट्रेसबैक + +Rich [खूबसूरत ट्रेसबैक](https://rich.readthedocs.io/en/latest/traceback.html) दर्शा सकता है जो पढ़ने में आसान तथा मानक Python ट्रेसबैकों से अधिक कोड दिखाता है। आप Rich को व्यक्तीक्रम ट्रेसबैक संचालक भी निर्धारित कार सकते हैं ताकि सभी बेपकड़ अपवाद Rich के द्वारा प्रदर्शित हों। + +OSX (Linux पर समान) पर यह कुछ इस प्रकार दिखता है: +![traceback](https://github.com/willmcgugan/rich/raw/master/imgs/traceback.png) + +
+ +सभी Rich प्रतिपाद्य [कॉनसोल प्रोटोकॉल](https://rich.readthedocs.io/en/latest/protocol.html) का उपयोग करते हैं, जिसे आप स्वयं की Rich सामग्री बनाने के लिए भी इस्तेमाल कार सकते हैं। + +# उद्यम के लिए Rich + +Tidelift Subscription के हिस्से के तौर पर उपलब्ध। + +Rich एवं सहस्त्रों और संग्रहों के पालक आपके अनुप्रयोगों को बनाने के लिए इस्तेमाल किए जाने वाले खुले स्त्रोत संग्रहों के लिए व्यावसायिक सहायता तथा रखरखाव देने के लिए Tidelift के साथ काम कार रहे हैं। समय बचाइए, जोखिम काम कीजिए, और कोड स्वास्थ सुधारें, और साथ में जिन संग्रहों को आप इस्तेमाल करते हैं उनके पालकों को भुगतान करें। [अधिक जानें।](https://tidelift.com/subscription/pkg/pypi-rich?utm_source=pypi-rich&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +# Rich का उपयोग करने वाली परियोजनाएँ + +ये रहे कुछ परियोजनाएँ जो Rich इस्तेमाल करते हैं। +- [BrancoLab/BrainRender](https://github.com/BrancoLab/BrainRender) + त्रिविम न्यूरो-संरचनात्मक डेटा का चित्रण करने के लिए एक Python संग्रह +- [Ciphey/Ciphey](https://github.com/Ciphey/Ciphey) + स्वचालित विकोडन उपकरण +- [emeryberger/scalene](https://github.com/emeryberger/scalene) + Python के लिए एक उच्च-प्रदर्शन, उच्च-सूक्ष्मता CPU एवं स्मृति प्रोफाइलर +- [hedythedev/StarCli](https://github.com/hedythedev/starcli) + अपनी आदेश पंक्ति (कमांड लाइन) से GitHub रुझानि परियोजिनाएं ब्राउज़ करें +- [intel/cve-bin-tool](https://github.com/intel/cve-bin-tool) + यह उपकरण कई साधारण, भेद्य घटकों (openssl, libpng, libxml2, expat और कुछ और) के लिए जांच करता है ताकि आपको बता सके की क्या आपके तंत्र में जानी हुई कमज़ोरियों वाले संग्रह युक्त हैं। +- [nf-core/tools](https://github.com/nf-core/tools) + nf-core समुदाय के लिए सहायक उपकरणों युक्त Python संग्रह +- [cansarigol/pdbr](https://github.com/cansarigol/pdbr) + उन्नत दोषमार्जन के लिए pdb + Rich संग्रह +- [plant99/felicette](https://github.com/plant99/felicette) + पुतलों के लिए उपग्रह चित्र +- [seleniumbase/SeleniumBase](https://github.com/seleniumbase/SeleniumBase) + Selenium और pytest के साथ १० गुना तेज़ स्वचालन एवं परीक्षण करें। बैटरी शामिल। +- [smacke/ffsubsync](https://github.com/smacke/ffsubsync) + स्वतः उपशीर्षकों को वीडियो के साथ समकालित करें। +- [tryolabs/norfair](https://github.com/tryolabs/norfair) + किसी भी संसूचक में सद्य-अनुक्रिया द्विविम वस्तु ट्रैकिंग जोड़ने के लिए एक हल्का Python संग्रह। +- [ansible/ansible-lint](https://github.com/ansible/ansible-lint) + Ansible-lint उन आचरणों और व्यवहारों के लिए प्लेबुकों में जाँच करता है जिन्हे संभावित रूप से सुधारा जा सकता है +- [ansible-community/molecule](https://github.com/ansible-community/molecule) Ansible Molecule testing framework + Ansible Molecule परीक्षण ढांचा +- +[कई और](https://github.com/willmcgugan/rich/network/dependents)! + + diff --git a/README.ja.md b/README.ja.md index dfbebe6b7..5a94d1108 100644 --- a/README.ja.md +++ b/README.ja.md @@ -1,10 +1,14 @@ -# Rich - +[![Downloads](https://pepy.tech/badge/rich/month)](https://pepy.tech/project/rich) [![PyPI version](https://badge.fury.io/py/rich.svg)](https://badge.fury.io/py/rich) [![codecov](https://codecov.io/gh/willmcgugan/rich/branch/master/graph/badge.svg)](https://codecov.io/gh/willmcgugan/rich) [![Rich blog](https://img.shields.io/badge/blog-rich%20news-yellowgreen)](https://www.willmcgugan.com/tag/rich/) [![Twitter Follow](https://img.shields.io/twitter/follow/willmcgugan.svg?style=social)](https://twitter.com/willmcgugan) +![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg) + +[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) • [Français readme](https://github.com/willmcgugan/rich/blob/master/README.fr.md) • [Schwizerdütsch readme](https://github.com/willmcgugan/rich/blob/master/README.de-ch.md) • [हिन्दी readme](https://github.com/willmcgugan/rich/blob/master/README.hi.md) + • [Português brasileiro readme](https://github.com/willmcgugan/rich/blob/master/README.pt-br.md) + Richは、_リッチ_なテキストや美しい書式設定をターミナルで行うためのPythonライブラリです。 [Rich API](https://rich.readthedocs.io/en/latest/)を使用すると、ターミナルの出力に色やスタイルを簡単に追加することができます。 Richはきれいなテーブル、プログレスバー、マークダウン、シンタックスハイライトされたソースコード、トレースバックなどをすぐに生成・表示することもできます。 diff --git a/README.kr.md b/README.kr.md index 19d8f5b04..5d80bf75b 100644 --- a/README.kr.md +++ b/README.kr.md @@ -6,7 +6,8 @@ ![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg) -[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme ](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) +[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) • [Français readme](https://github.com/willmcgugan/rich/blob/master/README.fr.md) • [Schwizerdütsch readme](https://github.com/willmcgugan/rich/blob/master/README.de-ch.md) • [हिन्दी readme](https://github.com/willmcgugan/rich/blob/master/README.hi.md) + • [Português brasileiro readme](https://github.com/willmcgugan/rich/blob/master/README.pt-br.md) Rich는 터미널에서 _풍부한(rich)_ 텍스트와 아름다운 서식을 지원하기 위한 파이썬 라이브러리입니다. @@ -444,4 +445,4 @@ Rich를 사용하는 몇가지 프로젝트들입니다: Ansible Molecule의 테스트 프레임워크 - +[Many more](https://github.com/willmcgugan/rich/network/dependents)! - \ No newline at end of file + diff --git a/README.md b/README.md index 880d2544d..daaa5b398 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,8 @@ ![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg) -[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) +[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) • [Français readme](https://github.com/willmcgugan/rich/blob/master/README.fr.md) • [Schwizerdütsch readme](https://github.com/willmcgugan/rich/blob/master/README.de-ch.md) • [हिन्दी readme](https://github.com/willmcgugan/rich/blob/master/README.hi.md) + • [Português brasileiro readme](https://github.com/willmcgugan/rich/blob/master/README.pt-br.md) Rich is a Python library for _rich_ text and beautiful formatting in the terminal. @@ -287,7 +288,7 @@ The spinner animations were borrowed from [cli-spinners](https://www.npmjs.com/p python -m rich.spinner ``` -The above command generate the following output in the terminal: +The above command generates the following output in the terminal: ![spinners](https://github.com/willmcgugan/rich/raw/master/imgs/spinners.gif) diff --git a/README.pt-br.md b/README.pt-br.md new file mode 100644 index 000000000..3de7a7892 --- /dev/null +++ b/README.pt-br.md @@ -0,0 +1,449 @@ +[![Downloads](https://pepy.tech/badge/rich/month)](https://pepy.tech/project/rich) +[![PyPI version](https://badge.fury.io/py/rich.svg)](https://badge.fury.io/py/rich) +[![codecov](https://codecov.io/gh/willmcgugan/rich/branch/master/graph/badge.svg)](https://codecov.io/gh/willmcgugan/rich) +[![Rich blog](https://img.shields.io/badge/blog-rich%20news-yellowgreen)](https://www.willmcgugan.com/tag/rich/) +[![Twitter Follow](https://img.shields.io/twitter/follow/willmcgugan.svg?style=social)](https://twitter.com/willmcgugan) + +![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg) + +[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) • [Français readme](https://github.com/willmcgugan/rich/blob/master/README.fr.md) • [Schwizerdütsch readme](https://github.com/willmcgugan/rich/blob/master/README.de-ch.md) • [हिन्दी readme](https://github.com/willmcgugan/rich/blob/master/README.hi.md) + • [Português brasileiro readme](https://github.com/willmcgugan/rich/blob/master/README.pt-br.md) + +Rich é uma biblioteca Python para _rich_ text e formatação de estilos no termial. + +A [API do Rich](https://rich.readthedocs.io/en/latest/) permite adicionar cores e estilos no output do termial de forma fácil. Rich também permite formataçao de tabelas, barra de progresso, markdown, highlight de sintaxe de código fonte, rastreio de erros (traceback), e muito mais. + +![Funcões](https://github.com/willmcgugan/rich/raw/master/imgs/features.png) + +Para mais detalhes, veja um vídeo de introdução so Rick em [calmcode.io](https://calmcode.io/rich/introduction.html) por [@fishnets88](https://twitter.com/fishnets88). + +Veja aqui [o que estão falando sobre o Rich](https://www.willmcgugan.com/blog/pages/post/rich-tweets/). + +## Compatibilidade + +Rich funciona no Linux, OSX e Windows. True color / emoji funciona no novo Terminal do Windows, o terminal classico é limitado a 16 cores. Rich requer Python 3.6.1 or later. + +Rich funciona com [Jupyter notebooks](https://jupyter.org/) sem a necessidade de configurações adicionais. + +## Instalação + +Instale usando `pip` ou seu gerenciador de pacotes PyPi favorito. + +``` +pip install rich +``` + +Execute o seguinte comando para testar o output do Rich no seu terminal: + +``` +python -m rich +``` + +## Print do Rich + +Para adicionar as as funções de formatação do rich na sua aplicação de forma fácil, simplesmente importe o metodo [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start) que tem a mesma assinatura da função nativa do Python. Por exemplo: + +```python +from rich import print + +print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals()) +``` + +![Hello World](https://github.com/willmcgugan/rich/raw/master/imgs/print.png) + +## REPL do Rich + +O Rich pode ser instalado no REPL do Python fazendo com que qualquer estrutura de dados seja exibida formatada e com highlights. + +```python +>>> from rich import pretty +>>> pretty.install() +``` + +![REPL](https://github.com/willmcgugan/rich/raw/master/imgs/repl.png) + +## Usando o Console + +Para ter mais controle sobre a formatação do conteudo no terminal, importe e instancie um objeto do [Console](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console). + +```python +from rich.console import Console + +console = Console() +``` + +Objetos do tipo Console tem um metodo `print` que tem a interface intencionalmente similar à função `print` nativa. Veja a seguir um exeplo de uso: + +```python +console.print("Hello", "World!") +``` + +Como esperado, este comando vai imprimir `"Hello World!"` no terminal. Porém, observe que, diferente da função `print` nativa, o Rich vai quebrar a linha entre palavras (word-wrap) no seu texto para caber na largura do terminal. + +Existem algumas formas de adicionar cores e estilos nos outputs. É possivel aplicar um estilo para todo output adicionando o argumento nomeado `style`. Por exemplo: + +```python +console.print("Hello", "World!", style="bold red") +``` + +O resultado vai ser algo como: + +![Hello World](https://github.com/willmcgugan/rich/raw/master/imgs/hello_world.png) + +Isso funciona bem para formatar cada linha do texto individualmente. Para maior controle sobre a formatação, o Rich renderiza um markup especial com uma sintaxe similar ao [bbcode](https://en.wikipedia.org/wiki/BBCode). Veja o exemplo a seguir: + +```python +console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].") +``` + +![Console Markup](https://github.com/willmcgugan/rich/raw/master/imgs/where_there_is_a_will.png) + +Voce pode usar o objeto do Console para gerar facilmente uma saída para o terminal sofisticada. Veja a documentação da [API do Console](https://rich.readthedocs.io/en/latest/console.html) para mais detalhes. + +## Inspect do Rich + +O Rich tem uma função [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) que gera um relatório de qualquer objeto no Python, como classes, instancias ou funções nativas. + +```python +>>> my_list = ["foo", "bar"] +>>> from rich import inspect +>>> inspect(my_list, methods=True) +``` + +![Log](https://github.com/willmcgugan/rich/raw/master/imgs/inspect.png) + +Confira a [documentação do inspect](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect) para mais detalhes. + +# A biblioteca Rich + +O Rich possui vários _renderizaveis_ nativos que podem ser usados para criar outputs elegantes no seu CLI e ajudar a debugar o código. + +Clique nos itens a seguir para expandir os detalhes: + +
+Log + +O objeto Console tem um método `log()` com uma interface similar ao `print()` mas que também imprime uma coluna com a hora atual, nome do arquivo e linha onde foi executado. Por padrão, o Rich vai fazer highlight de sintaxe para extruturas do Python e para repr strings. Se você usar o `log()` para imprimir uma _collection_ (por exemplo um dicionário ou uma lista), o Rich vai imprimir formatado de uma forma que caiba no espaço disponível. Veja a seguir alguns exemplos dessas funções: + +```python +from rich.console import Console +console = Console() + +test_data = [ + {"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "id": "1",}, + {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}, + {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": "2"}, +] + +def test_log(): + enabled = False + context = { + "foo": "bar", + } + movies = ["Deadpool", "Rise of the Skywalker"] + console.log("Hello from", console, "!") + console.log(test_data, log_locals=True) + + +test_log() +``` + +O código acima vai produzir algo parecido com: + +![Log](https://github.com/willmcgugan/rich/raw/master/imgs/log.png) + +Note o argumento `log_locals` que imprime uma tabela com as variáveis locais no contexto em que o método `log()` foi chamado. + +O método `log()` pode ser usado para logar no terminal em aplicações de processos longos como servidores, mas é também uma ferramenta ótima para debugar. + +
+
+Logging Handler + +Você também pode usar a [classe Handler](https://rich.readthedocs.io/en/latest/logging.html) nativa para formatar e colorir o output do módulo `logging` do Python. Veja aqui um exemplo do output: + +![Logging](https://github.com/willmcgugan/rich/raw/master/imgs/logging.png) + +
+ +
+Emoji + +Para imprimir um emoji no console, coloque o nome do emoji entre dois ":" (dois pontos). Por exemplo: + +```python +>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:") +😃 🧛 💩 👍 🦝 +``` + +Please use this feature wisely. + +
+ +
+Tabelas + +O Rich pode imprimir [tables](https://rich.readthedocs.io/en/latest/tables.html) flexiveis usando caracteres unicode como bordas. Existem várias opções de formatação de bordas, estilos, alinhamento das celulas etc. + +![table movie](https://github.com/willmcgugan/rich/raw/master/imgs/table_movie.gif) + +A animação acima foi gerada com o arquivo [table_movie.py](https://github.com/willmcgugan/rich/blob/master/examples/table_movie.py) da pasta de exeplos. + +Veja um exemplo mais simple: + +```python +from rich.console import Console +from rich.table import Table + +console = Console() + +table = Table(show_header=True, header_style="bold magenta") +table.add_column("Date", style="dim", width=12) +table.add_column("Title") +table.add_column("Production Budget", justify="right") +table.add_column("Box Office", justify="right") +table.add_row( + "Dev 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118" +) +table.add_row( + "May 25, 2018", + "[red]Solo[/red]: A Star Wars Story", + "$275,000,000", + "$393,151,347", +) +table.add_row( + "Dec 15, 2017", + "Star Wars Ep. VIII: The Last Jedi", + "$262,000,000", + "[bold]$1,332,539,889[/bold]", +) + +console.print(table) +``` + +Que gera o seguinte resultado: + +![table](https://github.com/willmcgugan/rich/raw/master/imgs/table.png) + +Observe que o markup é renderizado da mesma for que em `print()` e `log()`. De fato, tudo que é renderizável pelo Rich pode ser incluído nos cabeçalhos ou linhas (até mesmo outras tabelas). + +A class `Table` é inteligente o suficiente para ajustar o tamanho das colunas para caber na largura do terminal, quebrando o texto em novas linhas como necessário. Veja a seguir o mesmo exemplo, só que desta vez com um terminal menor do que o tamanho original da tabela: + +![table2](https://github.com/willmcgugan/rich/raw/master/imgs/table2.png) + +
+ +
+Barra de Progresso + +O Rich consegue renderizar de forma eficiente multiplas barras de [progresso](https://rich.readthedocs.io/en/latest/progress.html) que podem ser usadas para rastrear o estado de processos longos. + +Uma forma simples de usar é passando o iterável para a função `track` e iterar normalmente sobre o retorno. Veja o exemplo a seguir: + +```python +from rich.progress import track + +for step in track(range(100)): + do_step(step) +``` + +It's not much harder to add multiple progress bars. Here's an example taken from the docs: +Adicionar multiplas barras de progresso também é simples. Veja outro exemplo que existe na documentação: + +![progress](https://github.com/willmcgugan/rich/raw/master/imgs/progress.gif) + +As colunas podem ser configuradas pra mostrar qualquer detalho necessário. As colunas nativas incluem a porcentagem completa, tamanho de arquivo, velocidade do arquivo e tempo restante. O exemplo a seguir mostra o progresso de um download: + +![progress](https://github.com/willmcgugan/rich/raw/master/imgs/downloader.gif) + +Para testar isso no seu terminal, use o arquivo [examples/downloader.py](https://github.com/willmcgugan/rich/blob/master/examples/downloader.py) para fazer o download de multiplas URLs simultaneamente, exibindo o progress de cada download. + +
+ +
+Status + +Em casos em que é dificil de calcular o progresso da tarefa, você pode usar o método [status](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) que exibe uma animação de um "spinner" e a mensagem. A animação não impede em nada o uso do `console`. Veja o exemplo a seguir: + +```python +from time import sleep +from rich.console import Console + +console = Console() +tasks = [f"task {n}" for n in range(1, 11)] + +with console.status("[bold green]Working on tasks...") as status: + while tasks: + task = tasks.pop(0) + sleep(1) + console.log(f"{task} complete") +``` + +Este código resultará no seguinte output no terminal: + +![status](https://github.com/willmcgugan/rich/raw/master/imgs/status.gif) + +As animações do "spinner" foram emprestadas do [cli-spinners](https://www.npmjs.com/package/cli-spinners). É possível escolher um estilo de "spinner" usando o parametro `spinner`. Execute o comando a seguir para ver todos os tipos de "spinner" disponíveis. + +``` +python -m rich.spinner +``` + +O comando acima deve exibir o seguinte no seu terminal: + +![spinners](https://github.com/willmcgugan/rich/raw/master/imgs/spinners.gif) + +
+ +
+Árvore + +O Rich pode renderizar [árvores](https://rich.readthedocs.io/en/latest/tree.html) com linhas de identação. Uma árvore é a forma ideal de exibir uma extrutura de arquivos ou qualquer outra apresentação hierárquica de dados. + +Os titulos dos itens da árvore podem ser textos simples ou qualquer coisa que o Rich pode renderizar. Execute o comando a seguir para uma demonstração: + +``` +python -m rich.tree +``` + +Isso gera o seguinte resultado: + +![markdown](https://github.com/willmcgugan/rich/raw/master/imgs/tree.png) + +Veja o exemplo em [tree.py](https://github.com/willmcgugan/rich/blob/master/examples/tree.py) de um script that displays a tree view of any directory, similar to the linux `tree` command. +Veja o exemplo em [tree.py](https://github.com/willmcgugan/rich/blob/master/examples/tree.py) de um código que gera uma árvore de exibição de um dicionário, semelhante ao comando `tree` do linux. + +
+ +
+Colunas + +O Rich pode renderizar conteúdos em [colunas](https://rich.readthedocs.io/en/latest/columns.html) bem formatadas com tamanhos iguais ou otimizados. O exemplo a seguir é uma cópia básica do comando `ls` (presente no MacOS / Linux) que mostra o conteúdo de uma pasta organizado em colunas: + +```python +import os +import sys + +from rich import print +from rich.columns import Columns + +directory = os.listdir(sys.argv[1]) +print(Columns(directory)) +``` + +The following screenshot is the output from the [columns example](https://github.com/willmcgugan/rich/blob/master/examples/columns.py) which displays data pulled from an API in columns: +O screenshot a seguir é do resultado do [exemplo de colunas](https://github.com/willmcgugan/rich/blob/master/examples/columns.py) formatando em colunas os dados extraidos de uma API: + +![columns](https://github.com/willmcgugan/rich/raw/master/imgs/columns.png) + +
+ +
+Markdown + +O Rich pode renderizar [markdown](https://rich.readthedocs.io/en/latest/markdown.html) e faz um bom trabalho de conversão do formato para o terminal. + +Para renderizar markdowm, importe a classe `Markdown` e instancie com a string que contem o código markdown. Depois, imprima o objeto no console. Por exemplo: + +```python +from rich.console import Console +from rich.markdown import Markdown + +console = Console() +with open("README.md") as readme: + markdown = Markdown(readme.read()) +console.print(markdown) +``` + +Isso produzirá um resultado como: + +![markdown](https://github.com/willmcgugan/rich/raw/master/imgs/markdown.png) + +
+ +
+Highlight de Sintaxe + +O Rich usa a biblioteca [pygments](https://pygments.org/) para implementar o [highlight de sintaxe](https://rich.readthedocs.io/en/latest/syntax.html). O uso é similar à renderização de markdown, instancie um objeto da classe `Syntax` imprima no console. Por exemplo: + +```python +from rich.console import Console +from rich.syntax import Syntax + +my_code = ''' +def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]: + """Iterate and generate a tuple with a flag for first and last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + first = True + for value in iter_values: + yield first, False, previous_value + first = False + previous_value = value + yield first, True, previous_value +''' +syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True) +console = Console() +console.print(syntax) +``` + +Este código gerará o seguinte resultado: + +![syntax](https://github.com/willmcgugan/rich/raw/master/imgs/syntax.png) + +
+ +
+Rastreio de Erros (tracebacks) + +O Rich renderiza [tracebacks formatados](https://rich.readthedocs.io/en/latest/traceback.html) que são fáceis de ler e mostra mais código do que os tracebacks padrão do Python. É possivel configurar o Rich como o gerenciador padrão de tracebacks para que todas as excessões inesperadas sejam renderizadas pelo Rich. + +Veja o resultado disso no OSX (resultados semelhantes no Linux): + +![traceback](https://github.com/willmcgugan/rich/raw/master/imgs/traceback.png) + +
+ +Todos os renderizaveis do Rich usam o [Protocolo do Console](https://rich.readthedocs.io/en/latest/protocol.html), que você pode usar para implementar o seu próprio conteúdo Rich. + +# Rich para empresas + +Disponível como parte da assinatura Tidelift. + +Os mantenedores do Rich e milhares de outros pacotes estão trabalhando com o Tidelift para disponibilizar suporte comercial e manutenção de projetos de código aberto usados nas suas aplicações. Economise tempo, reduza riscos e melhore a saúde do código enquanto paga os mantenedores dos pacotes exatos que você usa. [Mais detalhes.](https://tidelift.com/subscription/pkg/pypi-rich?utm_source=pypi-rich&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +# Projetos usando Rich + +Aqui estão alguns projetos que usam o Rich: + +- [BrancoLab/BrainRender](https://github.com/BrancoLab/BrainRender) + a python package for the visualization of three dimensional neuro-anatomical data + um pacote python para visualisação tridimensional de dados neuro-atômicos. +- [Ciphey/Ciphey](https://github.com/Ciphey/Ciphey) + ferramenta de descriptografia autoatizada. +- [emeryberger/scalene](https://github.com/emeryberger/scalene) + um analisador de CPU e memória de alta performance e alta precisão para Python +- [hedythedev/StarCli](https://github.com/hedythedev/starcli) + Explore projetos de destaque no GitHub pela linha de comando do terminal +- [intel/cve-bin-tool](https://github.com/intel/cve-bin-tool) + Essa ferramenta verifica a vulnerabilidade de diversos componentes populares (openssl, libpng, libxml2, expat e outros) presentes no seu sistema e alerta para possíveis vulnerabilidades conhecidas. +- [nf-core/tools](https://github.com/nf-core/tools) + pacote Python com ferramentas auxiliares par a comunidade nf-core. +- [cansarigol/pdbr](https://github.com/cansarigol/pdbr) + pdb + Rich para auxiliar no debug +- [plant99/felicette](https://github.com/plant99/felicette) + Imagem de satélites para tolos. +- [seleniumbase/SeleniumBase](https://github.com/seleniumbase/SeleniumBase) + Automatize & teste 10x mais rápido com Selenium & pytest. Baterias inclusas. +- [smacke/ffsubsync](https://github.com/smacke/ffsubsync) + Automagicamente sincronize legendas com vídeos. +- [tryolabs/norfair](https://github.com/tryolabs/norfair) + Biblioteca Python para adicionar rastreio em tempo real de objetos 2D em qualquer detector. +- [ansible/ansible-lint](https://github.com/ansible/ansible-lint) Ansible-lint verifica boas praticas e comportamento que podem ser melhorados. +- [ansible-community/molecule](https://github.com/ansible-community/molecule) Framework de test para Ansible Molecule +- +[Muitos outros](https://github.com/willmcgugan/rich/network/dependents)! + + diff --git a/README.sv.md b/README.sv.md index 49ae56f76..21e8bb9bc 100644 --- a/README.sv.md +++ b/README.sv.md @@ -6,7 +6,8 @@ ![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg) -[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) +[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) • [Français readme](https://github.com/willmcgugan/rich/blob/master/README.fr.md) • [Schwizerdütsch readme](https://github.com/willmcgugan/rich/blob/master/README.de-ch.md) + • [Português brasileiro readme](https://github.com/willmcgugan/rich/blob/master/README.pt-br.md) Rich är ett Python bibliotek för _rich_ text och vacker formattering i terminalen. diff --git a/docs/requirements.txt b/docs/requirements.txt index ca85e46e8..67cbc0079 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,4 +1,4 @@ alabaster==0.7.12 -Sphinx==4.1.1 +Sphinx==4.1.2 sphinx-rtd-theme==0.5.2 sphinx-copybutton==0.4.0 diff --git a/docs/source/live.rst b/docs/source/live.rst index 193dbeb25..f2c5cc76f 100644 --- a/docs/source/live.rst +++ b/docs/source/live.rst @@ -5,7 +5,7 @@ Live Display Progress bars and status indicators use a *live* display to animate parts of the terminal. You can build custom live displays with the :class:`~rich.live.Live` class. -For a demonstration of a live display, running the following command: +For a demonstration of a live display, run the following command: python -m rich.live @@ -16,7 +16,7 @@ For a demonstration of a live display, running the following command: Basic usage ~~~~~~~~~~~ -To create a live display, construct a :class:`~rich.live.Live` object with a renderable and use it has a context manager. The live display will persist for the duration of the context. You can update the renderable to update the display:: +To create a live display, construct a :class:`~rich.live.Live` object with a renderable and use it as a context manager. The live display will persist for the duration of the context. You can update the renderable to update the display:: import time diff --git a/docs/source/traceback.rst b/docs/source/traceback.rst index f1d46e39c..ee0d64bec 100644 --- a/docs/source/traceback.rst +++ b/docs/source/traceback.rst @@ -1,7 +1,11 @@ Traceback ========= -Rich can render Python tracebacks with syntax highlighting and formatting. Rich tracebacks are easier to read, and show more code, than standard Python tracebacks. +Rich can render Python tracebacks with syntax highlighting and formatting. Rich tracebacks are easier to read and show more code than standard Python tracebacks. + +To see an example of a Rich traceback, running the following command:: + + python -m rich.traceback Printing tracebacks @@ -9,10 +13,17 @@ Printing tracebacks The :meth:`~rich.console.Console.print_exception` method will print a traceback for the current exception being handled. Here's an example:: + from rich.console import Console + console = Console() + try: do_something() - except: - console.print_exception() + except Exception: + console.print_exception(show_locals=True) + +The ``show_locals=True`` parameter causes Rich to display the value of local variables for each frame of the traceback. + +See `exception.py `_ for a larger example. Traceback handler @@ -21,6 +32,6 @@ Traceback handler Rich can be installed as the default traceback handler so that all uncaught exceptions will be rendered with highlighting. Here's how:: from rich.traceback import install - install() + install(show_locals=True) -There are a few options to configure the traceback handler, see :func:`~rich.traceback.install` for details. \ No newline at end of file +There are a few options to configure the traceback handler, see :func:`~rich.traceback.install` for details. diff --git a/examples/exception.py b/examples/exception.py index 6bf2a1ebe..548432d66 100644 --- a/examples/exception.py +++ b/examples/exception.py @@ -16,21 +16,25 @@ def divide_by(number: float, divisor: float) -> float: def divide_all(divides: List[Tuple[float, float]]) -> None: """Do something impossible every day.""" - try: - for number, divisor in divides: + + for number, divisor in divides: + console.print(f"dividing {number} by {divisor}") + try: result = divide_by(number, divisor) - console.print(f"{number} divided by {divisor} is {result}") - except Exception: - console.print_exception(extra_lines=5, show_locals=True) + except Exception: + console.print_exception(extra_lines=8, show_locals=True) + else: + console.print(f" = {result}") DIVIDES = [ (1000, 200), (10000, 500), + (1, 0), (0, 1000000), (3.1427, 2), + (888, 0), (2 ** 32, 2 ** 16), - (1, 0), ] divide_all(DIVIDES) diff --git a/rich/emoji.py b/rich/emoji.py index c3c844ecc..d5a1062a9 100644 --- a/rich/emoji.py +++ b/rich/emoji.py @@ -25,7 +25,7 @@ class NoEmoji(Exception): class Emoji(JupyterMixin): - __slots__ = ["name", "style", "_char"] + __slots__ = ["name", "style", "_char", "variant"] VARIANTS = {"text": "\uFE0E", "emoji": "\uFE0F"} diff --git a/rich/jupyter.py b/rich/jupyter.py index cc0279797..7cdcc9cab 100644 --- a/rich/jupyter.py +++ b/rich/jupyter.py @@ -31,6 +31,8 @@ def _repr_mimebundle_( class JupyterMixin: """Add to an Rich renderable to make it render in Jupyter notebook.""" + __slots__ = () + def _repr_mimebundle_( self, include: Iterable[str], exclude: Iterable[str], **kwargs: Any ) -> Dict[str, str]: diff --git a/rich/segment.py b/rich/segment.py index 97ddc8d0a..8f5705b10 100644 --- a/rich/segment.py +++ b/rich/segment.py @@ -107,6 +107,12 @@ def _split_cells(cls, segment: "Segment", cut: int) -> Tuple["Segment", "Segment _Segment(text[cut:], style, control), ) + if len(text) == self.cell_length: + return ( + _Segment(text[:cut], style, control), + _Segment(text[cut:], style, control), + ) + cell_size = get_character_cell_size pos = int((cut / segment.cell_length) * len(text))