From 738105d6869338b7847d48897660d06e693ff172 Mon Sep 17 00:00:00 2001 From: Casper da Costa-Luis Date: Mon, 25 Jan 2016 21:25:43 +0000 Subject: [PATCH] pypy, py26 compatibility, update examples --- examples/simple_examples.py | 2 +- tqdm/_tqdm.py | 24 ++++++++++++++++++------ tqdm/tests/tests_tqdm.py | 6 +++++- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/examples/simple_examples.py b/examples/simple_examples.py index 5e3a525b..b84cf212 100644 --- a/examples/simple_examples.py +++ b/examples/simple_examples.py @@ -21,7 +21,7 @@ stmts = ( ' ascii=True, desc="cool", dynamic_ncols=True):\n\tpass', # Nested bars 'from tqdm import trange\nfor i in trange(10):\n\t' - 'for j in trange(int(1e7), nested=True):\n\t\tpass', + 'for j in trange(int(1e7), leave=False, unit_scale=True):\n\t\tpass', # Experimental GUI demo 'import tqdm\nfor i in tqdm.tgrange(int(1e8)):\n\tpass', # Comparison to https://code.google.com/p/python-progressbar/ diff --git a/tqdm/_tqdm.py b/tqdm/_tqdm.py index 097211fb..9e90126e 100644 --- a/tqdm/_tqdm.py +++ b/tqdm/_tqdm.py @@ -88,12 +88,17 @@ class tqdm(object): if not getattr(fp, 'flush', False): # pragma: no cover fp.flush = lambda: None + def fp_write(s): + try: + fp.write(_unicode(s)) + except UnicodeEncodeError: + fp.write(str(s)) + last_printed_len = [0] # closure over mutable variable (fast) def print_status(s): len_s = len(s) - fp.write(_unicode('\r' + s + - (' ' * max(last_printed_len[0] - len_s, 0)))) + fp_write('\r' + s + (' ' * max(last_printed_len[0] - len_s, 0))) fp.flush() last_printed_len[0] = len_s return print_status @@ -262,7 +267,7 @@ class tqdm(object): return max(inst.pos for inst in cls._instances if inst is not instance) + 1 except ValueError as e: - if "max() arg is an empty sequence" in str(e): + if "arg is an empty sequence" in str(e): return 0 raise # pragma: no cover @@ -700,8 +705,15 @@ class tqdm(object): if not hasattr(self, "sp"): return + # annoyingly, _supports_unicode isn't good enough + def fp_write(s): + try: + self.fp.write(_unicode(s)) + except UnicodeEncodeError: + self.fp.write(s) + try: - self.fp.write(_unicode('')) + fp_write('') except ValueError as e: if 'closed' in str(e): return @@ -723,13 +735,13 @@ class tqdm(object): if pos: self.moveto(-pos) else: - self.fp.write(_unicode('\n')) + fp_write('\n') else: self.sp('') # clear up last bar if pos: self.moveto(-pos) else: - self.fp.write(_unicode('\r')) + fp_write('\r') def unpause(self): """ diff --git a/tqdm/tests/tests_tqdm.py b/tqdm/tests/tests_tqdm.py index 8124c397..10e4ccb7 100644 --- a/tqdm/tests/tests_tqdm.py +++ b/tqdm/tests/tests_tqdm.py @@ -174,7 +174,11 @@ def test_all_defaults(): pass import sys # restore stdout/stderr output for `nosetest` interface - sys.stderr.write('\x1b[A\rTest default kwargs ... ') + try: + sys.stderr.write('\x1b[A') + except: + pass + sys.stderr.write('\rTest default kwargs ... ') @with_setup(pretest, posttest)