From 92571fb94e1482566a18d1680f8d692f6f431c9d Mon Sep 17 00:00:00 2001 From: Niru Maheswaranathan Date: Thu, 29 Sep 2016 14:50:40 -0700 Subject: [PATCH] Properly handles ANSI escape sequences in table rows --- .travis.yml | 1 + Makefile | 2 +- tableprint.py | 12 +++++++++--- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 0c48675..71b5f05 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,6 +5,7 @@ python: - "2.7" - "3.4" - "3.5" + - "3.6" addons: apt: packages: diff --git a/Makefile b/Makefile index 3a25467..1d73044 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,7 @@ upload: python setup.py sdist bdist_wininst upload test2: - python2 /usr/local/bin/nosetests --logging-level=INFO + python2 /Users/nirum/anaconda/bin/nosetests --logging-level=INFO test: nosetests -v --with-coverage --cover-package=tableprint --logging-level=INFO diff --git a/tableprint.py b/tableprint.py index 5762181..e46b58c 100644 --- a/tableprint.py +++ b/tableprint.py @@ -15,10 +15,11 @@ from six import string_types from collections import namedtuple from numbers import Number import sys +import re import numpy as np __all__ = ['table', 'header', 'row', 'hr', 'top', 'bottom', 'banner', 'dataframe', 'humantime'] -__version__ = '0.4.3' +__version__ = '0.5.0' # set up table styles LineStyle = namedtuple('LineStyle', ('begin', 'hline', 'sep', 'end')) @@ -149,7 +150,7 @@ def row(values, width=WIDTH, format_spec=FMT, style=STYLE): Parameters ---------- values : array_like - An iterable array of data (numbers of strings), each value is printed in a separate column + An iterable array of data (numbers or strings), each value is printed in a separate column width : int The width of each column (Default: 11) @@ -180,7 +181,7 @@ def row(values, width=WIDTH, format_spec=FMT, style=STYLE): datum, prec = val if isinstance(datum, string_types): - return ('{:>%i}' % width).format(datum) + return ('{:>%i}' % (width + _ansi_len(datum))).format(datum) elif isinstance(datum, Number): return ('{:>%i.%s}' % (width, prec)).format(datum) @@ -318,6 +319,11 @@ def humantime(t): return timestr +def _ansi_len(string): + """Extra length due to any ANSI sequences in the string.""" + return len(string) - len(re.compile(r'\x1b[^m]*m').sub('', string)) + + def _format_line(data, linestyle): """Formats a list of elements using the given line style""" return linestyle.begin + linestyle.sep.join(data) + linestyle.end