more docs

This commit is contained in:
Will McGugan 2019-12-30 22:08:02 +00:00
parent 2bb2500e62
commit a5731429c2
6 changed files with 116 additions and 39 deletions

3
docs/source/console.rst Normal file
View file

@ -0,0 +1,3 @@
Console API
===========

View file

@ -1,34 +1,55 @@
Introduction
============
Rich is a Python library for rendering *rich* text and formatting to the terminal. Use Rich to create slick command line applications and as a handy debugging aid.
Rich is a Python library for writing *rich* text (with color and formatting) to the terminal, and for rendering tables, markdown, and code with syntax highlighting.
Use Rich to make command line applications more visually appealing and present data in a more readable way. Rich can also be a useful debugging aid by pretty printing and syntax highlighting data structures.
Installation
------------
You may install Rich with your favorite PyPi package manager::
You can install Rich with your favorite PyPi package manager::
pip install rich
Add the ``-U`` switch to update to the current version, if rich is already installed.
Add the ``-U`` switch to update to the current version, if Rich is already installed.
Quick Start
-----------
The quickest way to get up and running with Rich is to use the alternative ``print`` function, which can be used as a drop-in replacement for Python's built in function. Here's how you would do that::
The quickest way to get up and running with Rich is to import the alternative ``print`` function, which can be used as a drop-in replacement for Python's built in function. Here's how you would do that::
from rich import print
You can then print content to the terminal in the same way as usual. Rich will add the time and file/line number where print was called. It will also format and syntax highlight any Python objects you print.
You can then print content to the terminal in the usual way. Rich will pretty print and syntax highlight any Python objects you print, and display the file/line where the print function was called.
If you would rather not shadow Python's builtin print, you can import rich.print as ``rprint`` (for example)::
Strings may contain :ref:`console_markup` which can be used to easily insert color and styles in to the output.
The following demonstrates both console markup and pretty formatting of Python objects::
>>> print("[red]*Hello*[/red] World!", locals())
This writes the following output to the terminal (including all the colors and styles):
.. raw:: html
<pre style="font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #800000; font-style: italic">Hello</span> World! <span style="color: #7f7f7f">&lt;stdin&gt;:1</span>
<span style="font-weight: bold">{</span>
<span style="color: #008000">'__annotations__'</span>: <span style="font-weight: bold">{}</span>,
<span style="color: #008000">'__builtins__'</span>: <span style="font-weight: bold"><</span><span style="color: #ff00ff">module</span><span style="color: #000000"> </span><span style="color: #008000">'builtins'</span><span style="color: #000000"> </span><span style="color: #000000; font-weight: bold">(</span><span style="color: #000000">built-in</span><span style="color: #000000; font-weight: bold">)</span><span style="font-weight: bold">></span>,
<span style="color: #008000">'__doc__'</span>: <span style="color: #800080; font-style: italic">None</span>,
<span style="color: #008000">'__loader__'</span>: <span style="font-weight: bold"><</span><span style="color: #ff00ff">class</span><span style="color: #000000"> </span><span style="color: #008000">'_frozen_importlib.BuiltinImporter'</span><span style="font-weight: bold">></span>,
<span style="color: #008000">'__name__'</span>: <span style="color: #008000">'__main__'</span>,
<span style="color: #008000">'__package__'</span>: <span style="color: #800080; font-style: italic">None</span>,
<span style="color: #008000">'__spec__'</span>: <span style="color: #800080; font-style: italic">None</span>,
<span style="color: #008000">'print'</span>: <span style="font-weight: bold"><</span><span style="color: #ff00ff">function</span><span style="color: #000000"> print at </span><span style="color: #000080; font-weight: bold">0x1027fd4c0</span><span style="font-weight: bold">></span>,
<span style="font-weight: bold">}</span> </pre>
If you would rather not shadow Python's builtin print, you can import ``rich.print`` as ``rprint`` (for example)::
from rich import print as rprint
For more control over formatting, create a :ref:`rich.console.Console` object::
from rich.console import Console
console = Console()
console.print("Hello, **World**! :smiley:")
Continue reading to learn about the more advanced features of Rich.

View file

@ -1,3 +1,5 @@
.. _console_markup:
Console Markup
==============

View file

@ -19,9 +19,9 @@ def print(
if _console is None:
from .console import Console
_console = Console()
_console = Console(log_time=False)
write_console = _console if file is None else Console(file=file)
write_console = _console if file is None else Console(log_time=False, file=file)
return write_console.log(
*objects, sep=sep, end=end, log_locals=log_locals, _stack_offset=2
)

View file

@ -152,7 +152,22 @@ COLOR_SYSTEMS = {
class Console:
"""A high level console interface."""
"""A high level console interface.
Args:
color_system (str, optional): The color system supported by your terminal,
either ``"standard"``, ``"256"`` or ``"truecolor"``. Leave as ``"auto"`` to autodetect.
styles (Dict[str, Style], optional): An optional mapping of style name strings to :class:`~rich.style.Style` objects.
file (IO, optional): A file object where the console shoudl write to. Defaults to stdoutput.
width (int, optional): The width of the terminal. Leave as default to auto-detect width.
height (int, optional): The height of the terminal. Leave as default to auto-detect height.
record (bool, optional): Boolean to enable recording of terminal output,
required to call :meth:`export_html` and :meth:`export_text`. Defaults to False.
markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True.
log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True.
log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True.
log_time_format (str, optional): Log time format if ``log_time`` is enabled. Defaults to "[%X] ".
"""
def __init__(
self,
@ -169,6 +184,20 @@ class Console:
log_path: bool = True,
log_time_format: str = "[%X] ",
):
"""[summary]
Args:
color_system (Optional[Literal[, optional): [description]. Defaults to "auto".
styles (Dict[str, Style], optional): [description]. Defaults to None.
file (IO, optional): [description]. Defaults to None.
width (int, optional): [description]. Defaults to None.
height (int, optional): [description]. Defaults to None.
record (bool, optional): [description]. Defaults to False.
markup (bool, optional): [description]. Defaults to True.
log_time (bool, optional): [description]. Defaults to True.
log_path (bool, optional): [description]. Defaults to True.
log_time_format (str, optional): [description]. Defaults to "[%X] ".
"""
self._styles = ChainMap(DEFAULT_STYLES if styles is None else styles)
self.file = file or sys.stdout
@ -236,7 +265,7 @@ class Console:
@property
def encoding(self) -> str:
"""Get the encoding of the console file.
"""Get the encoding of the console file, e.g. ``"utf-8"``.
Returns:
str: A standard encoding string.
@ -309,7 +338,6 @@ class Console:
This method contains the logic for rendering objects with the console protocol.
You are unlikely to need to use it directly, unless you are extending the library.
Args:
renderable (RenderableType): An object supporting the console protocol, or
@ -422,7 +450,8 @@ class Console:
"""
if self._markup:
return markup.render(text)
return Text(text)
return markup.render_text(text)
def _get_style(self, name: str) -> Optional[Style]:
"""Get a named style, or `None` if it doesn't exist.
@ -592,14 +621,17 @@ class Console:
emoji=True,
highlight: "HighlighterType" = None,
) -> None:
"""Print to the console.
r"""Print to the console.
Args:
*objects: Arbitrary objects to print to the console.
sep (str, optional): Separator to print between objects. Defaults to " ".
end (str, optional): Character to end print with. Defaults to "\n".
style (Union[str, Style], optional):
objects (positional args): Objects to log to the terminal.
sep (str, optional): String to write between print data. Defaults to " ".
end (str, optional): String to write at end of print data. Defaults to "\n".
style (Union[str, Style], optional): A style to apply to output. Defaults to None.
emoji (bool): If True, emoji codes will be replaced, otherwise emoji codes will be left in.
highlight ([type], optional): A callable that accepts a :class:`~rich.text.Text` instance
and returns a Text instance, used to add highlighting. Defaults to None.
"""
if not objects:
self.line()
@ -621,12 +653,23 @@ class Console:
*objects: Any,
sep=" ",
end="\n",
debug=Ellipsis,
highlight: "HighlighterType" = None,
log_locals: bool = False,
_stack_offset=1,
) -> None:
if not objects and not debug:
r"""Log rich content to the terminal.
Args:
objects (positional args): Objects to log to the terminal.
sep (str, optional): String to write between print data. Defaults to " ".
end (str, optional): String to write at end of print data. Defaults to "\n".
highlight ([type], optional): A callable that accepts a :class:`~rich.text.Text` instance
and returns a Text instance, used to add highlighting. Defaults to None.
log_locals (bool, optional): Boolean to enable logging of locals where ``log()``
was called. Defaults to False.
_stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1.
"""
if not objects:
self.line()
return
highlighter = highlight or ReprHighlighter()
@ -634,9 +677,6 @@ class Console:
objects, sep=sep, end=end, highlight=highlighter
)
if debug != Ellipsis:
renderables.append(Pretty(debug))
caller = inspect.stack()[_stack_offset]
path = caller.filename.rpartition(os.sep)[-1]
line_no = caller.lineno
@ -685,9 +725,9 @@ class Console:
"""Generate text from console contents (requires record=True argument in constructor).
Args:
clear (bool, optional): Set to True to clear the record buffer after exporting.
styles (bool, optional): If True, ansi style codes will be included. False for plain text.
Defaults to False.
clear (bool, optional): Set to ``True`` to clear the record buffer after exporting.
styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text.
Defaults to ``False``.
Returns:
str: String containing console contents.
@ -712,9 +752,9 @@ class Console:
Args:
path (str): Path to write text files.
clear (bool, optional): Set to True to clear the record buffer after exporting.
styles (bool, optional): If True, ansi style codes will be included. False for plain text.
Defaults to False.
clear (bool, optional): Set to ``True`` to clear the record buffer after exporting.
styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text.
Defaults to ``False``.
"""
text = self.export_text(clear=clear, styles=styles)
@ -732,15 +772,15 @@ class Console:
Args:
theme (Theme, optional): Theme object containing console colors.
clear (bool, optional): Set to True to clear the record buffer after generating the HTML.
clear (bool, optional): Set to ``True`` to clear the record buffer after generating the HTML.
code_format (str, optional): Format string to render HTML, should contain {foreground}
{background} and {code}.
inline_styes (bool, optional): If True styles will be inlined in to spans, which makes files
larger but easier to cut and paste markup. If False, styles will be embedded in a style tag.
inline_styes (bool, optional): If ``True`` styles will be inlined in to spans, which makes files
larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.
Defaults to False.
Returns:
str: String containing console contents.
str: String containing console contents as HTML.
"""
assert (
self.record
@ -750,10 +790,15 @@ class Console:
_theme = theme or themes.DEFAULT
stylesheet = ""
def escape(text: str) -> str:
"""Escape html."""
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
render_code_format = CONSOLE_HTML_FORMAT if code_format is None else code_format
if inline_styles:
for text, style in Segment.simplify(self._record_buffer):
text = escape(text)
if style:
rule = style.get_html_style(_theme)
append(f'<span style="{rule}">{text}</span>' if rule else text)
@ -762,6 +807,7 @@ class Console:
else:
styles: Dict[str, int] = {}
for text, style in Segment.simplify(self._record_buffer):
text = escape(text)
if style:
rule = style.get_html_style(_theme)
if rule:
@ -804,8 +850,8 @@ class Console:
clear (bool, optional): Set to True to clear the record buffer after generating the HTML.
code_format (str, optional): Format string to render HTML, should contain {foreground}
{background} and {code}.
inline_styes (bool, optional): If True styles will be inlined in to spans, which makes files
larger but easier to cut and paste markup. If False, styles will be embedded in a style tag.
inline_styes (bool, optional): If ``True`` styles will be inlined in to spans, which makes files
larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.
Defaults to False.
"""

View file

@ -59,6 +59,11 @@ def _parse(markup: str) -> Iterable[Tuple[Optional[str], Optional[str]]]:
yield markup[position:], None
def render_text(markup: str, style: Union[str, Style] = "") -> Text:
"""Convert markup to Text instance."""
return Text(markup, style=style)
def render(markup: str, style: Union[str, Style] = "") -> Text:
"""Render console markup in to a Text instance.