Skip to main content

Extensions to the print function for pretty-printing with a layout engine.

Project description

About

The command line is a powerful user interface. Just by lining things up and using colors judiciously, you can greatly improve the user experience.

The standard python print() function is too simple. It barely provides any functionally more than just using sys.stdout.write(). This library aims to boost the functionally/complexity ratio of the print() function.

This is a set of objects for laying out and styling fixed-width text. The primary use-case is for pretty-printing text to the console to improve console application user interfaces. But, it can work equally well for any other stream, such as files.

The goal, as always, is to be simple to use the majority of the time while still allowing complex behavior.

Quick Reference

Use

>>> from print_ext import print, Flattener
>>> print = Flattener(width=80) # This is only needed to pass doctests.  Normally just use the print from print_ext.
>>> print('\b1 Hello', ' ', '\b2 World')
Hello World
<Printer>

Pretty Printing

Lists and dicts can be pretty-printed.

>>> print.pretty({'the':'quick', 'brown':['fox', {'jumped':'over', 'the':'lazy'}, 'dog']})
  the quick
brown [0] fox
      [1] jumped over
             the lazy
      [2] dog
<Printer>

Progress

>>> files = ['a.txt', 'cats.gif', 'sound.mp3']
>>> p = print.progress(steps=len(files), ascii=True)
>>> for f in files:
...    p('Process \b2$', f, '\b$ ...')
 ##########-------------------- Process a.txt...
 ####################---------- Process cats.gif...
 ############################## Process sound.mp3...
>>> p('\bg! Processing complete!', done=True)
 ############################## Processing complete!

If you don’t know how many steps it will take then a spinner is drawn.

>>> p = print.progress()
>>> for i in range(3):
...    p('thinking...', i)
thinking...0
thinking...1
thinking...2
>>> p(done=True)
<BLANKLINE>

Styles

Styles can be applied in two ways: as a keyword parameter, and inline using the escape character \b.

>>> print('bold ', '\br red-bold ', 'just-bold', style='!')
bold red-bold just-bold
<Printer>

Normally the \b syntax applies only to the string it is defined in. But adding a $ to the end extends the influence to the end of the call.

>>> print('white \bb$ blue', ' still blue ', '\b_ blue-underlined', ' just-blue')
white blue still blue blue-underlined just-blue
<Printer>

You can prematurely stop the style with an empty \b or \b$.

>>> print('white \b; dim \b\by$ not-dim-yellow ', 'still-yellow \b$ not-yellow')
white dim not-dim-yellow still-yellow not-yellow
<Printer>

The color codes are: blac(k), (r)ed, (g)reen, (y)ellow, (b)lue, (m)agenta, (c)yan, (w)hite. bold(!), not-bold(.), dim(;), not-dim(,), underline(_), reset(0)

Background colors are prefixed with a (^).

>>> print('\bg^c; dim-green-text-on-cyan \b0 back-to-normal ', '\b;! bold-dim \b, bold-not-dim')
dim-green-text-on-cyan back-to-normal bold-dim bold-not-dim
<Printer>

Instead of specifying styles directly, it is recommended to use named styles: err, warn, em, dem, 1, 2, 3.

>>> print('\bem emphasized ', '\bdem de-emphasized ', '\b1 primary-accent ', '\b2 secondary-accent ', '\b3 etc...')
emphasized de-emphasized primary-accent secondary-accent etc...
<Printer>

<hr/>

>>> print.hr()
────────────────────────────────────────────────────────────────────────────────
<Printer>
>>> print.hr('\b1 Hello\nWorld', border_style='2')
 │ Hello │
─┤ World ├──────────────────────────────────────────────────────────────────────
<Printer>

Vertical and horizontal justification can also be applied.

>>> print.hr('\b1 3...\n2...\n1...\n\br! Blastoff!', just='<^')
─┤ 3...      ├──────────────────────────────────────────────────────────────────
 │ 2...      │
 │ 1...      │
 │ Blastoff! │
<Printer>

The lines drawn are taken from the border context variable.

>>> print.hr('BOLD', border=('#','-.rl'))
━┥ BOLD ┝━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
<Printer>
>>> print.hr("This\nall looks right\njustified", border=' ', just='>')
                                                                         This
                                                              all looks right
                                                                    justified
<Printer>

Tables

>>> from print_ext import Table
>>> tbl = Table(0, 0)
>>> tbl('Hello\tWorld\tこんにちは\t世界\t')
<Table>
>>> print(tbl)
Hello      World
こんにちは 世界
<Printer>

The positional arguments to the Table() call indicate the widths of the columns. Negative integers specify a fixed-width column. Positive integers set the minimum width and a flex_rate of 1.0. A floating point value specifies the flex_rate

The tmpl keyword argument specifies a base-set of cell() calls. See Table.define_tmpl()

>>> tbl = Table(-6, 4, 10000.0, tmpl='grid')
>>> tbl('1\tThe quick \nbrown fox\tApples\t');
<Table>
>>> tbl('Too long\tjumped over the lazy dog\tBananas\t')
<Table>
>>> print(tbl)
┌─────┬────────────────────────┬───────┐
│1    │The quick               │Apples │
│     │brown fox               │       │
├─────┼────────────────────────┼───────┤
│Too l│jumped over the lazy dog│Bananas│
│⤷ ong│                        │       │
└─────┴────────────────────────┴───────┘
<Printer>
>>> tbl.cell('R0', just='>')
>>> print(tbl)
┌─────┬────────────────────────┬───────┐
│    1│              The quick │ Apples│
│     │               brown fox│       │
├─────┼────────────────────────┼───────┤
│Too l│jumped over the lazy dog│Bananas│
│⤷ ong│                        │       │
└─────┴────────────────────────┴───────┘
<Printer>
>>> tbl.cell('C0', just='_', style='y', wrap=False)
>>> print(tbl)
┌─────┬────────────────────────┬───────┐
│     │              The quick │ Apples│
│    1│               brown fox│       │
├─────┼────────────────────────┼───────┤
│To…ng│jumped over the lazy dog│Bananas│
└─────┴────────────────────────┴───────┘
<Printer>

Cards

The first cell is the title and the following cells are the body. So if you don’t want a title then tab quickly to the body.

>>> print.card('\tHello\nWorld!')
┌────────┐
│ Hello  │
│ World! │
└────────┘
<Printer>
>>> print.card('\berr Danger', '!\t', "Don't hold plutonium\nwith bare hands.")
┌┤ Danger! ├───────────┐
│ Don't hold plutonium │
│ with bare hands.     │
└──────────────────────┘
<Printer>

Flex

A flex, like a Table, uses tab characters to move from cell to cell.

>>> print.flex('The\nquick brown fox\tJumps over the\n lazy', '\t dog')
The            Jumps over the dog
quick brown fox lazy
<Printer>
>>> from print_ext import Bdr
>>> bdr = Bdr(border=('m:0001','-.r'), flex_rate=0)
>>> print.flex(bdr('\berr Error: '), '\t', 'The quick brown\nfox jumped over\nthe lazy\ndog.')
Error: │The quick brown
       │fox jumped over
       │the lazy
       │dog.
<Printer>

Installation

$ pip install print-ext
https://img.shields.io/pypi/v/print-ext.svg https://img.shields.io/pypi/pyversions/print-ext.svg

Design decisions

Mutable objects:

It is nice to be able to call a widget multiple times tbl(...) to add more data. This causes some complications when you try to add some widget to multiple other widgets.

Process-global CVars:

Context variables can be added to any widget even if it isn’t aware of that CVar. If you write a custom widget that uses custom CVars then we need to be able to assign that variable on any widget. This means that there can’t be any namespaces for the CVar names. If there is concern of name clashing then use prefix_based_namespacing.

Performance:

This is designed for human consumption, so it is only fast enough that humans don’t get impatient. It favors flexibility over performance.

Test

$ hatch shell
$ pytest

License

print-ext is distributed under the terms of the MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

print_ext-0.13.1.tar.gz (45.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

print_ext-0.13.1-py3-none-any.whl (36.5 kB view details)

Uploaded Python 3

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page