Merge pull request #20 from tqdm/dynamic_width

Set ncols from terminal environs
This commit is contained in:
Hadrien Mary 2015-06-25 18:41:43 +02:00
commit bccfcd2345
2 changed files with 46 additions and 23 deletions

View File

@ -8,6 +8,7 @@ Usage:
...
"""
from __future__ import division, absolute_import
from ._utils import _supports_unicode, _environ_cols, _range, _unich
import sys
import time
@ -17,16 +18,6 @@ __author__ = {"github.com/": ["noamraph", "JackMc", "arkottke", "obiwanus",
__all__ = ['tqdm', 'trange', 'format_interval', 'format_meter']
def _is_utf(encoding):
return ('U8' == encoding) or ('utf' in encoding) or ('UTF' in encoding)
def _supports_unicode(file):
if not getattr(file, 'encoding', None):
return False
return _is_utf(file.encoding)
def format_interval(t):
mins, s = divmod(int(t), 60)
h, m = divmod(mins, 60)
@ -90,13 +81,8 @@ def format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False):
else:
bar_length, frac_bar_length = divmod(int(frac * N_BARS * 8), 8)
try: # pragma: no cover
unich = unichr
except NameError: # pragma: no cover
unich = chr
bar = unich(0x2588)*bar_length
frac_bar = unich(0x2590 - frac_bar_length) \
bar = _unich(0x2588)*bar_length
frac_bar = _unich(0x2590 - frac_bar_length) \
if frac_bar_length else ' '
if bar_length < N_BARS:
@ -175,6 +161,9 @@ def tqdm(iterable, desc=None, total=None, leave=False, file=sys.stderr,
except (TypeError, AttributeError):
total = None
if (ncols is None) and (file in (sys.stderr, sys.stdout)):
ncols = _environ_cols()
if miniters is None:
miniters = 0
dynamic_miniters = True
@ -223,9 +212,4 @@ def trange(*args, **kwargs):
A shortcut for tqdm(xrange(*args), **kwargs).
On Python3+ range is used instead of xrange.
"""
try: # pragma: no cover
f = xrange
except NameError: # pragma: no cover
f = range
return tqdm(f(*args), **kwargs)
return tqdm(_range(*args), **kwargs)

39
tqdm/_utils.py Normal file
View File

@ -0,0 +1,39 @@
try: # pragma: no cover
_range = xrange
except NameError: # pragma: no cover
_range = range
try: # pragma: no cover
_unich = unichr
except NameError: # pragma: no cover
_unich = chr
def _is_utf(encoding):
return ('U8' == encoding) or ('utf' in encoding) or ('UTF' in encoding)
def _supports_unicode(file):
if not getattr(file, 'encoding', None):
return False
return _is_utf(file.encoding)
def _environ_cols(): # pragma: no cover
try:
from termios import TIOCGWINSZ
from fcntl import ioctl
from array import array
except ImportError:
return None
else:
try:
return array('h', ioctl(file, TIOCGWINSZ, '\0' * 8))[1]
except:
try:
from os.environ import get
except ImportError:
return None
else:
return int(get('COLUMNS', 1)) - 1