From 13c16b03c69858393f7068ea5fb3baa6a1c6c66e Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Sat, 2 May 2020 19:27:47 +0200 Subject: [PATCH] Don't insert spurious newlines in DummyTqdmFile. Only call `tqdm.write` (which inserts a newline) if `DummyTqdmFile.write` is itself called with a string containing a newline; otherwise buffer the rest of the string. See changes in test_tqdm.py for the patterns this allows. --- tqdm/contrib/__init__.py | 14 +++++++++++--- tqdm/tests/tests_tqdm.py | 9 ++++++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/tqdm/contrib/__init__.py b/tqdm/contrib/__init__.py index 01312cd05..d6a4a45ad 100644 --- a/tqdm/contrib/__init__.py +++ b/tqdm/contrib/__init__.py @@ -15,10 +15,18 @@ class DummyTqdmFile(ObjectWrapper): """Dummy file-like that will write to tqdm""" + def __init__(self, wrapped): + super(DummyTqdmFile, self).__init__(wrapped) + self._buf = [] + def write(self, x, nolock=False): - # Avoid print() second call (useless \n) - if len(x.rstrip()) > 0: - tqdm.write(x, file=self._wrapped, nolock=nolock) + pre, sep, post = x.rpartition("\n") + if sep: + tqdm.write("".join(self._buf) + pre, + file=self._wrapped, nolock=nolock) + self._buf = [post] + else: + self._buf.append(x) def tenumerate(iterable, start=0, total=None, tqdm_class=tqdm_auto, diff --git a/tqdm/tests/tests_tqdm.py b/tqdm/tests/tests_tqdm.py index a2dac529e..fcc976e2c 100644 --- a/tqdm/tests/tests_tqdm.py +++ b/tqdm/tests/tests_tqdm.py @@ -2,6 +2,7 @@ # Advice: use repr(our_file.read()) to print the full output of tqdm # (else '\r' will replace the previous lines and you'll see only the latest. +from __future__ import print_function import sys import csv import re @@ -1749,8 +1750,14 @@ def test_file_redirection(): with closing(StringIO()) as our_file: # Redirect stdout to tqdm.write() with std_out_err_redirect_tqdm(tqdm_file=our_file): - for _ in trange(3): + with tqdm(total=3) as pbar: print("Such fun") + pbar.update(1) + print("Such", "fun") + pbar.update(1) + print("Such ", end="") + print("fun") + pbar.update(1) res = our_file.getvalue() assert res.count("Such fun\n") == 3 assert "0/3" in res