-
Python rich: Console 출력 색깔, 꾸미기컴퓨터/파이썬 2020. 12. 13. 13:10728x90반응형
rich
1. 소개
rich-console은 python으로 powershell이나 cmd 출력 창을 꾸미는 라이브러리이다.
설치
pip install rich
2. 예제
API 문서 링크: @링크
dictionary, 함수 local value 출력
from rich.console import Console 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"}, ] console = Console() def log(): enabled = False context = { "foo": "bar", } movies = ["Deadpool", "Rise of the Skywalker"] console.log("Hello from", console, "!") console.log(data, log_locals=True) log()
기본 print 대체
from bigO import BigO from rich import print dic = { "USER": "ikr", "TEXT": "I found a :beer:, where I can copy my items over and over.", } print(dic) print(f"My array: [bold magenta]{BigO.genRandomString(10)}[/bold magenta]") print("NAVER: [blue underline]https://www.naver.com/")
테이블
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)
MD 파일 출력
from rich.console import Console from rich.markdown import Markdown console = Console() with open('RICH-MARKDOWN.md') as readme: markdown = Markdown(readme.read()) console.print(markdown)
다운로드 진행 바
""" A rudimentary URL downloader (like wget or curl) to demonstrate Rich progress bars. """ from concurrent.futures import ThreadPoolExecutor from functools import partial import os.path import sys from typing import Iterable from urllib.request import urlopen from rich.progress import ( BarColumn, DownloadColumn, TextColumn, TransferSpeedColumn, TimeRemainingColumn, Progress, TaskID, ) progress = Progress( TextColumn("[bold blue]{task.fields[filename]}", justify="right"), BarColumn(bar_width=None), "[progress.percentage]{task.percentage:>3.1f}%", "•", DownloadColumn(), "•", TransferSpeedColumn(), "•", TimeRemainingColumn(), ) def copy_url(task_id: TaskID, url: str, path: str) -> None: """Copy data from a url to a local file.""" response = urlopen(url) # This will break if the response doesn't contain content length progress.update(task_id, total=int(response.info()["Content-length"])) with open(path, "wb") as dest_file: progress.start_task(task_id) for data in iter(partial(response.read, 32768), b""): dest_file.write(data) progress.update(task_id, advance=len(data)) def download(urls: Iterable[str], dest_dir: str): """Download multuple files to the given directory.""" with progress: with ThreadPoolExecutor(max_workers=4) as pool: for url in urls: filename = url.split("/")[-1] dest_path = os.path.join(dest_dir, filename) task_id = progress.add_task("download", filename=filename, start=False) pool.submit(copy_url, task_id, url, dest_path) if __name__ == "__main__": # Try with https://releases.ubuntu.com/20.04/ubuntu-20.04-desktop-amd64.iso if sys.argv[1:]: download(sys.argv[1:], "./") else: print("Usage:\n\tpython downloader.py URL1 URL2 URL3 (etc)")
Syntax Highlighter
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)
728x90'컴퓨터 > 파이썬' 카테고리의 다른 글
Python: Kafka + 대학교 공지 Parser + Slack API + MySQL (0) 2020.12.15 Python: with문 만들어 사용하기 (0) 2020.12.11 파이썬: Tarjan 알고리즘 (Strongly Connected Components) (2) 2020.11.23