Skip to content

Commit 8ab081d

Browse files
committed
Consider ANSI escape codes when calculating the text length
1 parent 7075248 commit 8ab081d

3 files changed

Lines changed: 14 additions & 4 deletions

File tree

progressbar/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
from datetime import date
22

3-
from .utils import streams
3+
from .utils import (
4+
len_color,
5+
streams
6+
)
47
from .shortcuts import progressbar
58

69
from .widgets import (
@@ -41,6 +44,7 @@
4144
__date__ = str(date.today())
4245
__all__ = [
4346
'progressbar',
47+
'len_color',
4448
'streams',
4549
'Timer',
4650
'ETA',

progressbar/bar.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,9 +230,9 @@ class ProgressBar(StdRedirectMixin, ResizableMixin, ProgressBarBase):
230230
_DEFAULT_MAXVAL = base.UnknownLength
231231
_MINIMUM_UPDATE_INTERVAL = 0.05 # update up to a 20 times per second
232232

233-
def __init__(self, min_value=0, max_value=None,
234-
widgets=None, left_justify=True, initial_value=0,
235-
poll_interval=None, widget_kwargs=None, custom_len=len,
233+
def __init__(self, min_value=0, max_value=None, widgets=None,
234+
left_justify=True, initial_value=0, poll_interval=None,
235+
widget_kwargs=None, custom_len=utils.len_color,
236236
max_error=True, prefix=None, suffix=None, **kwargs):
237237
'''
238238
Initializes a progress bar with sane defaults

progressbar/utils.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import absolute_import
22
import io
33
import os
4+
import re
45
import sys
56
import logging
67
from python_utils.time import timedelta_to_seconds, epoch, format_time
@@ -17,6 +18,11 @@
1718
assert epoch
1819

1920

21+
def len_color(text):
22+
'''Return the length of text without ANSI escape codes'''
23+
return len(re.sub(u'\u001b\[.*?[@-~]', '', text))
24+
25+
2026
class WrappingIO:
2127

2228
def __init__(self, target, capturing=False, listeners=set()):

0 commit comments

Comments
 (0)