pax_global_header 0000666 0000000 0000000 00000000064 14254343417 0014521 g ustar 00root root 0000000 0000000 52 comment=4892c6e9a79638c7897ccea68b602040da9cc7a7
python-tabulate-0.8.10/ 0000775 0000000 0000000 00000000000 14254343417 0014727 5 ustar 00root root 0000000 0000000 python-tabulate-0.8.10/.circleci/ 0000775 0000000 0000000 00000000000 14254343417 0016562 5 ustar 00root root 0000000 0000000 python-tabulate-0.8.10/.circleci/config.yml 0000664 0000000 0000000 00000002735 14254343417 0020561 0 ustar 00root root 0000000 0000000 # Python CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-python/ for more details
#
version: 2
jobs:
build:
docker:
# specify the version you desire here
# use `-browsers` prefix for selenium tests, e.g. `3.6.1-browsers`
- image: circleci/python:3.8
# Specify service dependencies here if necessary
# CircleCI maintains a library of pre-built images
# documented at https://circleci.com/docs/2.0/circleci-images/
# - image: circleci/postgres:9.4
working_directory: ~/repo
steps:
- checkout
# Download and cache dependencies
- restore_cache:
keys:
- v1-dependencies-{{ checksum ".circleci/requirements.txt" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
- run:
name: install dependencies
command: |
python3 -m venv venv
. venv/bin/activate
pip install -r .circleci/requirements.txt
- save_cache:
paths:
- ./venv
key: v1-dependencies-{{ checksum ".circleci/requirements.txt" }}
- run:
name: run tests
command: |
. venv/bin/activate
tox -e py38-extra
- run:
name: run linting
command: |
. venv/bin/activate
tox -e lint
- store_artifacts:
path: test-reports
destination: test-reports
python-tabulate-0.8.10/.circleci/requirements.txt 0000664 0000000 0000000 00000000040 14254343417 0022040 0 ustar 00root root 0000000 0000000 pytest
tox
numpy
pandas
wcwidth
python-tabulate-0.8.10/.gitignore 0000664 0000000 0000000 00000000267 14254343417 0016724 0 ustar 00root root 0000000 0000000 build
dist
.tox
*~
*.pyc
/tabulate.egg-info/
*.egg*
*.pyc
.*
build/
.coverage
coverage.xml
dist/
doc/changelog.rst
venv*
website-build/
## Unit test / coverage reports
.coverage
.tox
python-tabulate-0.8.10/.pre-commit-config.yaml 0000664 0000000 0000000 00000000564 14254343417 0021215 0 ustar 00root root 0000000 0000000 repos:
- repo: https://github.com/python/black
rev: 19.3b0
hooks:
- id: black
args: [--safe]
language_version: python3
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.2.3
hooks:
- id: trailing-whitespace
- id: check-yaml
- id: debug-statements
- id: flake8
language_version: python3
python-tabulate-0.8.10/CHANGELOG 0000664 0000000 0000000 00000004244 14254343417 0016145 0 ustar 00root root 0000000 0000000 - 0.8.11: Future version
- 0.8.10: Python 3.10 support. Bug fixes.
- 0.8.9: Bug fix. Revert support of decimal separators.
- 0.8.8: Python 3.9 support, 3.10 ready.
New formats: ``unsafehtml``, ``latex_longtable``, ``fancy_outline``.
Support lists of UserDicts as input.
Support hyperlinks in terminal output.
Improve testing on systems with proxies.
Migrate to pytest.
Various bug fixes and improvements.
- 0.8.7: Bug fixes. New format: `pretty`. HTML escaping.
- 0.8.6: Bug fixes. Stop supporting Python 3.3, 3.4.
- 0.8.5: Fix broken Windows package. Minor documentation updates.
- 0.8.4: Bug fixes.
- 0.8.3: New formats: `github`. Custom colum alignment. Bug fixes.
- 0.8.2: Bug fixes.
- 0.8.1: Multiline data in several output formats.
New ``latex_raw`` format.
Column-specific floating point formatting.
Python 3.5 & 3.6 support. Drop support for Python 2.6, 3.2, 3.3 (should still work).
- 0.7.7: Identical to 0.7.6, resolving some PyPI issues.
- 0.7.6: Bug fixes. New table formats (``psql``, ``jira``, ``moinmoin``, ``textile``).
Wide character support. Printing from database cursors.
Option to print row indices. Boolean columns. Ragged rows.
Option to disable number parsing.
- 0.7.5: Bug fixes. ``--float`` format option for the command line utility.
- 0.7.4: Bug fixes. ``fancy_grid`` and ``html`` formats. Command line utility.
- 0.7.3: Bug fixes. Python 3.4 support. Iterables of dicts. ``latex_booktabs`` format.
- 0.7.2: Python 3.2 support.
- 0.7.1: Bug fixes. ``tsv`` format. Column alignment can be disabled.
- 0.7: ``latex`` tables. Printing lists of named tuples and NumPy
record arrays. Fix printing date and time values. Python <= 2.6.4 is supported.
- 0.6: ``mediawiki`` tables, bug fixes.
- 0.5.1: Fix README.rst formatting. Optimize (performance similar to 0.4.4).
- 0.5: ANSI color sequences. Printing dicts of iterables and Pandas' dataframes.
- 0.4.4: Python 2.6 support.
- 0.4.3: Bug fix, None as a missing value.
- 0.4.2: Fix manifest file.
- 0.4.1: Update license and documentation.
- 0.4: Unicode support, Python3 support, ``rst`` tables.
- 0.3: Initial PyPI release. Table formats: ``simple``, ``plain``,
``grid``, ``pipe``, and ``orgtbl``.
python-tabulate-0.8.10/HOWTOPUBLISH 0000664 0000000 0000000 00000000466 14254343417 0016607 0 ustar 00root root 0000000 0000000 # update contributors and CHANGELOG in README
python3 benchmark.py # then update README
tox -e py33,py34,py36-extra
python3 setup.py sdist bdist_wheel
twine upload --repository-url https://test.pypi.org/legacy/ dist/*
twine upload dist/*
# tag version release
# bump version number in setup.py in tabulate.py
python-tabulate-0.8.10/LICENSE 0000664 0000000 0000000 00000002070 14254343417 0015733 0 ustar 00root root 0000000 0000000 Copyright (c) 2011-2020 Sergey Astanin and contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
python-tabulate-0.8.10/MANIFEST.in 0000664 0000000 0000000 00000000157 14254343417 0016470 0 ustar 00root root 0000000 0000000 include LICENSE
include README
include README.md
include CHANGELOG
include test/common.py
include benchmark.py
python-tabulate-0.8.10/README 0000777 0000000 0000000 00000000000 14254343417 0017061 2README.md ustar 00root root 0000000 0000000 python-tabulate-0.8.10/README.md 0000664 0000000 0000000 00000060152 14254343417 0016212 0 ustar 00root root 0000000 0000000 python-tabulate
===============
Pretty-print tabular data in Python, a library and a command-line
utility.
The main use cases of the library are:
- printing small tables without hassle: just one function call,
formatting is guided by the data itself
- authoring tabular data for lightweight plain-text markup: multiple
output formats suitable for further editing or transformation
- readable presentation of mixed textual and numeric data: smart
column alignment, configurable number formatting, alignment by a
decimal point
Installation
------------
To install the Python library and the command line utility, run:
pip install tabulate
The command line utility will be installed as `tabulate` to `bin` on
Linux (e.g. `/usr/bin`); or as `tabulate.exe` to `Scripts` in your
Python installation on Windows (e.g.
`C:\Python27\Scripts\tabulate.exe`).
You may consider installing the library only for the current user:
pip install tabulate --user
In this case the command line utility will be installed to
`~/.local/bin/tabulate` on Linux and to
`%APPDATA%\Python\Scripts\tabulate.exe` on Windows.
To install just the library on Unix-like operating systems:
TABULATE_INSTALL=lib-only pip install tabulate
On Windows:
set TABULATE_INSTALL=lib-only
pip install tabulate
Build status
------------
[](https://circleci.com/gh/astanin/python-tabulate/tree/master) [](https://ci.appveyor.com/project/astanin/python-tabulate/branch/master)
Library usage
-------------
The module provides just one function, `tabulate`, which takes a list of
lists or another tabular data type as the first argument, and outputs a
nicely formatted plain-text table:
>>> from tabulate import tabulate
>>> table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
... ["Moon",1737,73.5],["Mars",3390,641.85]]
>>> print(tabulate(table))
----- ------ -------------
Sun 696000 1.9891e+09
Earth 6371 5973.6
Moon 1737 73.5
Mars 3390 641.85
----- ------ -------------
The following tabular data types are supported:
- list of lists or another iterable of iterables
- list or another iterable of dicts (keys as columns)
- dict of iterables (keys as columns)
- two-dimensional NumPy array
- NumPy record arrays (names as columns)
- pandas.DataFrame
Examples in this file use Python2. Tabulate supports Python3 too.
### Headers
The second optional argument named `headers` defines a list of column
headers to be used:
>>> print(tabulate(table, headers=["Planet","R (km)", "mass (x 10^29 kg)"]))
Planet R (km) mass (x 10^29 kg)
-------- -------- -------------------
Sun 696000 1.9891e+09
Earth 6371 5973.6
Moon 1737 73.5
Mars 3390 641.85
If `headers="firstrow"`, then the first row of data is used:
>>> print(tabulate([["Name","Age"],["Alice",24],["Bob",19]],
... headers="firstrow"))
Name Age
------ -----
Alice 24
Bob 19
If `headers="keys"`, then the keys of a dictionary/dataframe, or column
indices are used. It also works for NumPy record arrays and lists of
dictionaries or named tuples:
>>> print(tabulate({"Name": ["Alice", "Bob"],
... "Age": [24, 19]}, headers="keys"))
Age Name
----- ------
24 Alice
19 Bob
### Row Indices
By default, only pandas.DataFrame tables have an additional column
called row index. To add a similar column to any other type of table,
pass `showindex="always"` or `showindex=True` argument to `tabulate()`.
To suppress row indices for all types of data, pass `showindex="never"`
or `showindex=False`. To add a custom row index column, pass
`showindex=rowIDs`, where `rowIDs` is some iterable:
>>> print(tabulate([["F",24],["M",19]], showindex="always"))
- - --
0 F 24
1 M 19
- - --
### Table format
There is more than one way to format a table in plain text. The third
optional argument named `tablefmt` defines how the table is formatted.
Supported table formats are:
- "plain"
- "simple"
- "github"
- "grid"
- "fancy\_grid"
- "pipe"
- "orgtbl"
- "jira"
- "presto"
- "pretty"
- "psql"
- "rst"
- "mediawiki"
- "moinmoin"
- "youtrack"
- "html"
- "unsafehtml"
- "latex"
- "latex\_raw"
- "latex\_booktabs"
- "latex\_longtable"
- "textile"
- "tsv"
`plain` tables do not use any pseudo-graphics to draw lines:
>>> table = [["spam",42],["eggs",451],["bacon",0]]
>>> headers = ["item", "qty"]
>>> print(tabulate(table, headers, tablefmt="plain"))
item qty
spam 42
eggs 451
bacon 0
`simple` is the default format (the default may change in future
versions). It corresponds to `simple_tables` in [Pandoc Markdown
extensions](http://johnmacfarlane.net/pandoc/README.html#tables):
>>> print(tabulate(table, headers, tablefmt="simple"))
item qty
------ -----
spam 42
eggs 451
bacon 0
`github` follows the conventions of GitHub flavored Markdown. It
corresponds to the `pipe` format without alignment colons:
>>> print(tabulate(table, headers, tablefmt="github"))
| item | qty |
|--------|-------|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
`grid` is like tables formatted by Emacs'
[table.el](http://table.sourceforge.net/) package. It corresponds to
`grid_tables` in Pandoc Markdown extensions:
>>> print(tabulate(table, headers, tablefmt="grid"))
+--------+-------+
| item | qty |
+========+=======+
| spam | 42 |
+--------+-------+
| eggs | 451 |
+--------+-------+
| bacon | 0 |
+--------+-------+
`fancy_grid` draws a grid using box-drawing characters:
>>> print(tabulate(table, headers, tablefmt="fancy_grid"))
╒════════╤═══════╕
│ item │ qty │
╞════════╪═══════╡
│ spam │ 42 │
├────────┼───────┤
│ eggs │ 451 │
├────────┼───────┤
│ bacon │ 0 │
╘════════╧═══════╛
`presto` is like tables formatted by Presto cli:
>>> print(tabulate(table, headers, tablefmt="presto"))
item | qty
--------+-------
spam | 42
eggs | 451
bacon | 0
`pretty` attempts to be close to the format emitted by the PrettyTables
library:
>>> print(tabulate(table, headers, tablefmt="pretty"))
+-------+-----+
| item | qty |
+-------+-----+
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
+-------+-----+
`psql` is like tables formatted by Postgres' psql cli:
>>> print(tabulate(table, headers, tablefmt="psql"))
+--------+-------+
| item | qty |
|--------+-------|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
+--------+-------+
`pipe` follows the conventions of [PHP Markdown
Extra](http://michelf.ca/projects/php-markdown/extra/#table) extension.
It corresponds to `pipe_tables` in Pandoc. This format uses colons to
indicate column alignment:
>>> print(tabulate(table, headers, tablefmt="pipe"))
| item | qty |
|:-------|------:|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
`orgtbl` follows the conventions of Emacs
[org-mode](http://orgmode.org/manual/Tables.html), and is editable also
in the minor orgtbl-mode. Hence its name:
>>> print(tabulate(table, headers, tablefmt="orgtbl"))
| item | qty |
|--------+-------|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
`jira` follows the conventions of Atlassian Jira markup language:
>>> print(tabulate(table, headers, tablefmt="jira"))
|| item || qty ||
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
`rst` formats data like a simple table of the
[reStructuredText](http://docutils.sourceforge.net/docs/user/rst/quickref.html#tables)
format:
>>> print(tabulate(table, headers, tablefmt="rst"))
====== =====
item qty
====== =====
spam 42
eggs 451
bacon 0
====== =====
`mediawiki` format produces a table markup used in
[Wikipedia](http://www.mediawiki.org/wiki/Help:Tables) and on other
MediaWiki-based sites:
>>> print(tabulate(table, headers, tablefmt="mediawiki"))
{| class="wikitable" style="text-align: left;"
|+
|-
! item !! align="right"| qty
|-
| spam || align="right"| 42
|-
| eggs || align="right"| 451
|-
| bacon || align="right"| 0
|}
`moinmoin` format produces a table markup used in
[MoinMoin](https://moinmo.in/) wikis:
>>> print(tabulate(table, headers, tablefmt="moinmoin"))
|| ''' item ''' || ''' quantity ''' ||
|| spam || 41.999 ||
|| eggs || 451 ||
|| bacon || ||
`youtrack` format produces a table markup used in Youtrack tickets:
>>> print(tabulate(table, headers, tablefmt="youtrack"))
|| item || quantity ||
| spam | 41.999 |
| eggs | 451 |
| bacon | |
`textile` format produces a table markup used in
[Textile](http://redcloth.org/hobix.com/textile/) format:
>>> print(tabulate(table, headers, tablefmt="textile"))
|_. item |_. qty |
|<. spam |>. 42 |
|<. eggs |>. 451 |
|<. bacon |>. 0 |
`html` produces standard HTML markup as an html.escape'd str
with a ._repr_html_ method so that Jupyter Lab and Notebook display the HTML
and a .str property so that the raw HTML remains accessible.
`unsafehtml` table format can be used if an unescaped HTML is required:
>>> print(tabulate(table, headers, tablefmt="html"))
item | qty |
spam | 42 |
eggs | 451 |
bacon | 0 |
`latex` format creates a `tabular` environment for LaTeX markup,
replacing special characters like `_` or `\` to their LaTeX
correspondents:
>>> print(tabulate(table, headers, tablefmt="latex"))
\begin{tabular}{lr}
\hline
item & qty \\
\hline
spam & 42 \\
eggs & 451 \\
bacon & 0 \\
\hline
\end{tabular}
`latex_raw` behaves like `latex` but does not escape LaTeX commands and
special characters.
`latex_booktabs` creates a `tabular` environment for LaTeX markup using
spacing and style from the `booktabs` package.
`latex_longtable` creates a table that can stretch along multiple pages,
using the `longtable` package.
### Column alignment
`tabulate` is smart about column alignment. It detects columns which
contain only numbers, and aligns them by a decimal point (or flushes
them to the right if they appear to be integers). Text columns are
flushed to the left.
You can override the default alignment with `numalign` and `stralign`
named arguments. Possible column alignments are: `right`, `center`,
`left`, `decimal` (only for numbers), and `None` (to disable alignment).
Aligning by a decimal point works best when you need to compare numbers
at a glance:
>>> print(tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]]))
----------
1.2345
123.45
12.345
12345
1234.5
----------
Compare this with a more common right alignment:
>>> print(tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]], numalign="right"))
------
1.2345
123.45
12.345
12345
1234.5
------
For `tabulate`, anything which can be parsed as a number is a number.
Even numbers represented as strings are aligned properly. This feature
comes in handy when reading a mixed table of text and numbers from a
file:
>>> import csv ; from StringIO import StringIO
>>> table = list(csv.reader(StringIO("spam, 42\neggs, 451\n")))
>>> table
[['spam', ' 42'], ['eggs', ' 451']]
>>> print(tabulate(table))
---- ----
spam 42
eggs 451
---- ----
To disable this feature use `disable_numparse=True`.
>>> print(tabulate.tabulate([["Ver1", "18.0"], ["Ver2","19.2"]], tablefmt="simple", disable_numparse=True))
---- ----
Ver1 18.0
Ver2 19.2
---- ----
### Custom column alignment
`tabulate` allows a custom column alignment to override the above. The
`colalign` argument can be a list or a tuple of `stralign` named
arguments. Possible column alignments are: `right`, `center`, `left`,
`decimal` (only for numbers), and `None` (to disable alignment).
Omitting an alignment uses the default. For example:
>>> print(tabulate([["one", "two"], ["three", "four"]], colalign=("right",))
----- ----
one two
three four
----- ----
### Number formatting
`tabulate` allows to define custom number formatting applied to all
columns of decimal numbers. Use `floatfmt` named argument:
>>> print(tabulate([["pi",3.141593],["e",2.718282]], floatfmt=".4f"))
-- ------
pi 3.1416
e 2.7183
-- ------
`floatfmt` argument can be a list or a tuple of format strings, one per
column, in which case every column may have different number formatting:
>>> print(tabulate([[0.12345, 0.12345, 0.12345]], floatfmt=(".1f", ".3f")))
--- ----- -------
0.1 0.123 0.12345
--- ----- -------
### Text formatting
By default, `tabulate` removes leading and trailing whitespace from text
columns. To disable whitespace removal, set the global module-level flag
`PRESERVE_WHITESPACE`:
import tabulate
tabulate.PRESERVE_WHITESPACE = True
### Wide (fullwidth CJK) symbols
To properly align tables which contain wide characters (typically
fullwidth glyphs from Chinese, Japanese or Korean languages), the user
should install `wcwidth` library. To install it together with
`tabulate`:
pip install tabulate[widechars]
Wide character support is enabled automatically if `wcwidth` library is
already installed. To disable wide characters support without
uninstalling `wcwidth`, set the global module-level flag
`WIDE_CHARS_MODE`:
import tabulate
tabulate.WIDE_CHARS_MODE = False
### Multiline cells
Most table formats support multiline cell text (text containing newline
characters). The newline characters are honored as line break
characters.
Multiline cells are supported for data rows and for header rows.
Further automatic line breaks are not inserted. Of course, some output
formats such as latex or html handle automatic formatting of the cell
content on their own, but for those that don't, the newline characters
in the input cell text are the only means to break a line in cell text.
Note that some output formats (e.g. simple, or plain) do not represent
row delimiters, so that the representation of multiline cells in such
formats may be ambiguous to the reader.
The following examples of formatted output use the following table with
a multiline cell, and headers with a multiline cell:
>>> table = [["eggs",451],["more\nspam",42]]
>>> headers = ["item\nname", "qty"]
`plain` tables:
>>> print(tabulate(table, headers, tablefmt="plain"))
item qty
name
eggs 451
more 42
spam
`simple` tables:
>>> print(tabulate(table, headers, tablefmt="simple"))
item qty
name
------ -----
eggs 451
more 42
spam
`grid` tables:
>>> print(tabulate(table, headers, tablefmt="grid"))
+--------+-------+
| item | qty |
| name | |
+========+=======+
| eggs | 451 |
+--------+-------+
| more | 42 |
| spam | |
+--------+-------+
`fancy_grid` tables:
>>> print(tabulate(table, headers, tablefmt="fancy_grid"))
╒════════╤═══════╕
│ item │ qty │
│ name │ │
╞════════╪═══════╡
│ eggs │ 451 │
├────────┼───────┤
│ more │ 42 │
│ spam │ │
╘════════╧═══════╛
`pipe` tables:
>>> print(tabulate(table, headers, tablefmt="pipe"))
| item | qty |
| name | |
|:-------|------:|
| eggs | 451 |
| more | 42 |
| spam | |
`orgtbl` tables:
>>> print(tabulate(table, headers, tablefmt="orgtbl"))
| item | qty |
| name | |
|--------+-------|
| eggs | 451 |
| more | 42 |
| spam | |
`jira` tables:
>>> print(tabulate(table, headers, tablefmt="jira"))
| item | qty |
| name | |
|:-------|------:|
| eggs | 451 |
| more | 42 |
| spam | |
`presto` tables:
>>> print(tabulate(table, headers, tablefmt="presto"))
item | qty
name |
--------+-------
eggs | 451
more | 42
spam |
`pretty` tables:
>>> print(tabulate(table, headers, tablefmt="pretty"))
+------+-----+
| item | qty |
| name | |
+------+-----+
| eggs | 451 |
| more | 42 |
| spam | |
+------+-----+
`psql` tables:
>>> print(tabulate(table, headers, tablefmt="psql"))
+--------+-------+
| item | qty |
| name | |
|--------+-------|
| eggs | 451 |
| more | 42 |
| spam | |
+--------+-------+
`rst` tables:
>>> print(tabulate(table, headers, tablefmt="rst"))
====== =====
item qty
name
====== =====
eggs 451
more 42
spam
====== =====
Multiline cells are not well supported for the other table formats.
### Automating Multilines
While tabulate supports data passed in with multiines entries explicitly provided,
it also provides some support to help manage this work internally.
The `maxcolwidths` argument is a list where each entry specifies the max width for
it's respective column. Any cell that will exceed this will automatically wrap the content.
To assign the same max width for all columns, a singular int scaler can be used.
Use `None` for any columns where an explicit maximum does not need to be provided,
and thus no automate multiline wrapping will take place.
The wraping uses the python standard [textwrap.wrap](https://docs.python.org/3/library/textwrap.html#textwrap.wrap)
function with default parameters - aside from width.
This example demonstrates usagage of automatic multiline wrapping, though typically
the lines being wrapped would probably be significantly longer than this.
>>> print(tabulate([["John Smith", "Middle Manager"]], headers=["Name", "Title"], tablefmt="grid", maxcolwidths=[None, 8]))
+------------+---------+
| Name | Title |
+============+=========+
| John Smith | Middle |
| | Manager |
+------------+---------+
Usage of the command line utility
---------------------------------
Usage: tabulate [options] [FILE ...]
FILE a filename of the file with tabular data;
if "-" or missing, read data from stdin.
Options:
-h, --help show this message
-1, --header use the first row of data as a table header
-o FILE, --output FILE print table to FILE (default: stdout)
-s REGEXP, --sep REGEXP use a custom column separator (default: whitespace)
-F FPFMT, --float FPFMT floating point number format (default: g)
-f FMT, --format FMT set output table format; supported formats:
plain, simple, github, grid, fancy_grid, pipe,
orgtbl, rst, mediawiki, html, latex, latex_raw,
latex_booktabs, latex_longtable, tsv
(default: simple)
Performance considerations
--------------------------
Such features as decimal point alignment and trying to parse everything
as a number imply that `tabulate`:
- has to "guess" how to print a particular tabular data type
- needs to keep the entire table in-memory
- has to "transpose" the table twice
- does much more work than it may appear
It may not be suitable for serializing really big tables (but who's
going to do that, anyway?) or printing tables in performance sensitive
applications. `tabulate` is about two orders of magnitude slower than
simply joining lists of values with a tab, comma, or other separator.
At the same time, `tabulate` is comparable to other table
pretty-printers. Given a 10x10 table (a list of lists) of mixed text and
numeric data, `tabulate` appears to be slower than `asciitable`, and
faster than `PrettyTable` and `texttable` The following mini-benchmark
was run in Python 3.8.2 in Ubuntu 20.04:
================================== ========== ===========
Table formatter time, μs rel. time
================================== ========== ===========
csv to StringIO 9.0 1.0
join with tabs and newlines 10.7 1.2
asciitable (0.8.0) 174.6 19.4
tabulate (0.8.10) 385.0 42.8
tabulate (0.8.10, WIDE_CHARS_MODE) 509.1 56.5
PrettyTable (3.3.0) 827.7 91.9
texttable (1.6.4) 952.1 105.7
================================== ========== ===========
Version history
---------------
The full version history can be found at the [changelog](https://github.com/astanin/python-tabulate/blob/master/CHANGELOG).
How to contribute
-----------------
Contributions should include tests and an explanation for the changes
they propose. Documentation (examples, docstrings, README.md) should be
updated accordingly.
This project uses [pytest](https://docs.pytest.org/) testing
framework and [tox](https://tox.readthedocs.io/) to automate testing in
different environments. Add tests to one of the files in the `test/`
folder.
To run tests on all supported Python versions, make sure all Python
interpreters, `pytest` and `tox` are installed, then run `tox` in the root
of the project source tree.
On Linux `tox` expects to find executables like `python2.6`,
`python2.7`, `python3.4` etc. On Windows it looks for
`C:\Python26\python.exe`, `C:\Python27\python.exe` and
`C:\Python34\python.exe` respectively.
To test only some Python environments, use `-e` option. For example, to
test only against Python 2.7 and Python 3.8, run:
tox -e py27,py38
in the root of the project source tree.
To enable NumPy and Pandas tests, run:
tox -e py27-extra,py38-extra
(this may take a long time the first time, because NumPy and Pandas will
have to be installed in the new virtual environments)
To fix code formatting:
tox -e lint
See `tox.ini` file to learn how to use to test
individual Python versions.
Contributors
------------
Sergey Astanin, Pau Tallada Crespí, Erwin Marsi, Mik Kocikowski, Bill
Ryder, Zach Dwiel, Frederik Rietdijk, Philipp Bogensberger, Greg
(anonymous), Stefan Tatschner, Emiel van Miltenburg, Brandon Bennett,
Amjith Ramanujam, Jan Schulz, Simon Percivall, Javier Santacruz
López-Cepero, Sam Denton, Alexey Ziyangirov, acaird, Cesar Sanchez,
naught101, John Vandenberg, Zack Dever, Christian Clauss, Benjamin
Maier, Andy MacKinlay, Thomas Roten, Jue Wang, Joe King, Samuel Phan,
Nick Satterly, Daniel Robbins, Dmitry B, Lars Butler, Andreas Maier,
Dick Marinus, Sébastien Celles, Yago González, Andrew Gaul, Wim Glenn,
Jean Michel Rouly, Tim Gates, John Vandenberg, Sorin Sbarnea,
Wes Turner, Andrew Tija, Marco Gorelli, Sean McGinnis, danja100,
endolith, Dominic Davis-Foster, pavlocat, Daniel Aslau, paulc,
Felix Yan, Shane Loretz, Frank Busse, Harsh Singh, Derek Weitzel,
Vladimir Vrzić, 서승우 (chrd5273), Georgy Frolov, Christian Cwienk,
Bart Broere, Vilhelm Prytz, Alexander Gažo, Hugo van Kemenade,
jamescooke, Matt Warner.
python-tabulate-0.8.10/appveyor.yml 0000664 0000000 0000000 00000003642 14254343417 0017324 0 ustar 00root root 0000000 0000000 environment:
matrix:
# For Python versions available on Appveyor, see
# https://www.appveyor.com/docs/windows-images-software/#python
# The list here is complete (excluding Python 2.6, which
# isn't covered by this document) at the time of writing.
- PYTHON: "C:\\Python27"
- PYTHON: "C:\\Python35"
- PYTHON: "C:\\Python36"
- PYTHON: "C:\\Python37"
- PYTHON: "C:\\Python38"
- PYTHON: "C:\\Python27-x64"
- PYTHON: "C:\\Python35-x64"
- PYTHON: "C:\\Python36-x64"
- PYTHON: "C:\\Python37-x64"
- PYTHON: "C:\\Python38-x64"
install:
# We need wheel installed to build wheels
- "%PYTHON%\\python.exe -m pip install wheel"
- "%PYTHON%\\python.exe -m pip install pytest numpy pandas"
build: off
test_script:
# Put your test command here.
# If you don't need to build C extensions on 64-bit Python 3.3 or 3.4,
# you can remove "build.cmd" from the front of the command, as it's
# only needed to support those cases.
# Note that you must use the environment variable %PYTHON% to refer to
# the interpreter you're using - Appveyor does not do anything special
# to put the Python version you want to use on PATH.
#- "build.cmd %PYTHON%\\python.exe setup.py test"
- "%PYTHON%\\python.exe -m pytest -v --doctest-modules --ignore benchmark.py"
after_test:
# This step builds your wheels.
# Again, you only need build.cmd if you're building C extensions for
# 64-bit Python 3.3/3.4. And you need to use %PYTHON% to get the correct
# interpreter
#- "build.cmd %PYTHON%\\python.exe setup.py bdist_wheel"
- "%PYTHON%\\python.exe setup.py sdist bdist_wheel"
artifacts:
# bdist_wheel puts your built wheel in the dist directory
- path: dist\*
#on_success:
# You can use this step to upload your artifacts to a public website.
# See Appveyor's documentation for more details. Or you can simply
# access your wheels from the Appveyor "artifacts" tab for your build.
python-tabulate-0.8.10/benchmark.py 0000664 0000000 0000000 00000005714 14254343417 0017242 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
from timeit import timeit
import tabulate
import asciitable
import prettytable
import texttable
import sys
import codecs
from platform import python_version_tuple
setup_code = r"""
from csv import writer
try: # Python 2
from StringIO import StringIO
except: # Python 3
from io import StringIO
import tabulate
import asciitable
import prettytable
import texttable
import platform
if platform.platform().startswith("Windows") \
and \
platform.python_version_tuple() < ('3','6','0'):
import win_unicode_console
win_unicode_console.enable()
table=[["some text"]+list(range(i,i+9)) for i in range(10)]
def csv_table(table):
buf = StringIO()
writer(buf).writerows(table)
return buf.getvalue()
def join_table(table):
return "\n".join(("\t".join(map(str,row)) for row in table))
def run_prettytable(table):
pp = prettytable.PrettyTable()
for row in table:
pp.add_row(row)
return str(pp)
def run_asciitable(table):
buf = StringIO()
asciitable.write(table, output=buf, Writer=asciitable.FixedWidth)
return buf.getvalue()
def run_texttable(table):
pp = texttable.Texttable()
pp.set_cols_align(["l"] + ["r"]*9)
pp.add_rows(table)
return pp.draw()
def run_tabletext(table):
return tabletext.to_text(table)
def run_tabulate(table, widechars=False):
tabulate.WIDE_CHARS_MODE = tabulate.wcwidth is not None and widechars
return tabulate.tabulate(table)
"""
methods = [
("join with tabs and newlines", "join_table(table)"),
("csv to StringIO", "csv_table(table)"),
("asciitable (%s)" % asciitable.__version__, "run_asciitable(table)"),
("tabulate (%s)" % tabulate.__version__, "run_tabulate(table)"),
(
"tabulate (%s, WIDE_CHARS_MODE)" % tabulate.__version__,
"run_tabulate(table, widechars=True)",
),
("PrettyTable (%s)" % prettytable.__version__, "run_prettytable(table)"),
("texttable (%s)" % texttable.__version__, "run_texttable(table)"),
]
if tabulate.wcwidth is None:
del methods[4]
def benchmark(n):
global methods
if "--onlyself" in sys.argv[1:]:
methods = [m for m in methods if m[0].startswith("tabulate")]
results = [
(desc, timeit(code, setup_code, number=n) / n * 1e6) for desc, code in methods
]
mintime = min(map(lambda x: x[1], results))
results = [
(desc, t, t / mintime) for desc, t in sorted(results, key=lambda x: x[1])
]
table = tabulate.tabulate(
results, ["Table formatter", "time, μs", "rel. time"], "rst", floatfmt=".1f"
)
from platform import platform
if platform().startswith("Windows"):
print(table)
elif python_version_tuple()[0] < "3":
print(codecs.encode(table, "utf-8"))
else:
print(table)
if __name__ == "__main__":
if sys.argv[1:]:
n = int(sys.argv[1])
else:
n = 10000
benchmark(n)
python-tabulate-0.8.10/setup.py 0000664 0000000 0000000 00000004354 14254343417 0016447 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from platform import python_version_tuple, python_implementation
import os
import re
# strip links from the descripton on the PyPI
if python_version_tuple()[0] >= "3":
LONG_DESCRIPTION = open("README.md", "r", encoding="utf-8").read()
else:
LONG_DESCRIPTION = open("README.md", "r").read()
# strip Build Status from the PyPI package
try:
if python_version_tuple()[:2] >= ("2", "7"):
status_re = "^Build status\n(.*\n){7}"
LONG_DESCRIPTION = re.sub(status_re, "", LONG_DESCRIPTION, flags=re.M)
except TypeError:
if python_implementation() == "IronPython":
# IronPython doesn't support flags in re.sub (IronPython issue #923)
pass
else:
raise
install_options = os.environ.get("TABULATE_INSTALL", "").split(",")
libonly_flags = set(["lib-only", "libonly", "no-cli", "without-cli"])
if libonly_flags.intersection(install_options):
console_scripts = []
else:
console_scripts = ["tabulate = tabulate:_main"]
setup(
name="tabulate",
version="0.8.10",
description="Pretty-print tabular data",
long_description=LONG_DESCRIPTION,
long_description_content_type="text/markdown",
author="Sergey Astanin",
author_email="s.astanin@gmail.com",
url="https://github.com/astanin/python-tabulate",
license="MIT",
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*",
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Topic :: Software Development :: Libraries",
],
py_modules=["tabulate"],
entry_points={"console_scripts": console_scripts},
extras_require={"widechars": ["wcwidth"]},
)
python-tabulate-0.8.10/tabulate.py 0000664 0000000 0000000 00000220241 14254343417 0017103 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
"""Pretty-print tabular data."""
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple
import sys
import re
import math
import textwrap
if sys.version_info >= (3, 3):
from collections.abc import Iterable
else:
from collections import Iterable
if sys.version_info[0] < 3:
from itertools import izip_longest
from functools import partial
_none_type = type(None)
_bool_type = bool
_int_type = int
_long_type = long # noqa
_float_type = float
_text_type = unicode # noqa
_binary_type = str
def _is_file(f):
return hasattr(f, "read")
else:
from itertools import zip_longest as izip_longest
from functools import reduce, partial
_none_type = type(None)
_bool_type = bool
_int_type = int
_long_type = int
_float_type = float
_text_type = str
_binary_type = bytes
basestring = str
import io
def _is_file(f):
return isinstance(f, io.IOBase)
try:
import wcwidth # optional wide-character (CJK) support
except ImportError:
wcwidth = None
try:
from html import escape as htmlescape
except ImportError:
from cgi import escape as htmlescape
__all__ = ["tabulate", "tabulate_formats", "simple_separated_format"]
__version__ = "0.8.10"
# minimum extra space in headers
MIN_PADDING = 2
# Whether or not to preserve leading/trailing whitespace in data.
PRESERVE_WHITESPACE = False
_DEFAULT_FLOATFMT = "g"
_DEFAULT_MISSINGVAL = ""
# default align will be overwritten by "left", "center" or "decimal"
# depending on the formatter
_DEFAULT_ALIGN = "default"
# if True, enable wide-character (CJK) support
WIDE_CHARS_MODE = wcwidth is not None
Line = namedtuple("Line", ["begin", "hline", "sep", "end"])
DataRow = namedtuple("DataRow", ["begin", "sep", "end"])
# A table structure is suppposed to be:
#
# --- lineabove ---------
# headerrow
# --- linebelowheader ---
# datarow
# --- linebetweenrows ---
# ... (more datarows) ...
# --- linebetweenrows ---
# last datarow
# --- linebelow ---------
#
# TableFormat's line* elements can be
#
# - either None, if the element is not used,
# - or a Line tuple,
# - or a function: [col_widths], [col_alignments] -> string.
#
# TableFormat's *row elements can be
#
# - either None, if the element is not used,
# - or a DataRow tuple,
# - or a function: [cell_values], [col_widths], [col_alignments] -> string.
#
# padding (an integer) is the amount of white space around data values.
#
# with_header_hide:
#
# - either None, to display all table elements unconditionally,
# - or a list of elements not to be displayed if the table has column headers.
#
TableFormat = namedtuple(
"TableFormat",
[
"lineabove",
"linebelowheader",
"linebetweenrows",
"linebelow",
"headerrow",
"datarow",
"padding",
"with_header_hide",
],
)
def _pipe_segment_with_colons(align, colwidth):
"""Return a segment of a horizontal line with optional colons which
indicate column's alignment (as in `pipe` output format)."""
w = colwidth
if align in ["right", "decimal"]:
return ("-" * (w - 1)) + ":"
elif align == "center":
return ":" + ("-" * (w - 2)) + ":"
elif align == "left":
return ":" + ("-" * (w - 1))
else:
return "-" * w
def _pipe_line_with_colons(colwidths, colaligns):
"""Return a horizontal line with optional colons to indicate column's
alignment (as in `pipe` output format)."""
if not colaligns: # e.g. printing an empty data frame (github issue #15)
colaligns = [""] * len(colwidths)
segments = [_pipe_segment_with_colons(a, w) for a, w in zip(colaligns, colwidths)]
return "|" + "|".join(segments) + "|"
def _mediawiki_row_with_attrs(separator, cell_values, colwidths, colaligns):
alignment = {
"left": "",
"right": 'align="right"| ',
"center": 'align="center"| ',
"decimal": 'align="right"| ',
}
# hard-coded padding _around_ align attribute and value together
# rather than padding parameter which affects only the value
values_with_attrs = [
" " + alignment.get(a, "") + c + " " for c, a in zip(cell_values, colaligns)
]
colsep = separator * 2
return (separator + colsep.join(values_with_attrs)).rstrip()
def _textile_row_with_attrs(cell_values, colwidths, colaligns):
cell_values[0] += " "
alignment = {"left": "<.", "right": ">.", "center": "=.", "decimal": ">."}
values = (alignment.get(a, "") + v for a, v in zip(colaligns, cell_values))
return "|" + "|".join(values) + "|"
def _html_begin_table_without_header(colwidths_ignore, colaligns_ignore):
# this table header will be suppressed if there is a header row
return "\n"
def _html_row_with_attrs(celltag, unsafe, cell_values, colwidths, colaligns):
alignment = {
"left": "",
"right": ' style="text-align: right;"',
"center": ' style="text-align: center;"',
"decimal": ' style="text-align: right;"',
}
if unsafe:
values_with_attrs = [
"<{0}{1}>{2}{0}>".format(celltag, alignment.get(a, ""), c)
for c, a in zip(cell_values, colaligns)
]
else:
values_with_attrs = [
"<{0}{1}>{2}{0}>".format(celltag, alignment.get(a, ""), htmlescape(c))
for c, a in zip(cell_values, colaligns)
]
rowhtml = "{}
".format("".join(values_with_attrs).rstrip())
if celltag == "th": # it's a header row, create a new table header
rowhtml = "\n\n{}\n\n".format(rowhtml)
return rowhtml
def _moin_row_with_attrs(celltag, cell_values, colwidths, colaligns, header=""):
alignment = {
"left": "",
"right": '