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.
This commit is contained in:
Antony Lee 2020-05-02 19:27:47 +02:00 committed by Casper da Costa-Luis
parent 37094ed020
commit 8e139fcf53
No known key found for this signature in database
GPG Key ID: 986B408043AE090D
2 changed files with 20 additions and 4 deletions

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
# 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 csv
import os
@ -1722,8 +1723,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

View File

@ -16,10 +16,19 @@ __all__ = ['tenumerate', 'tzip', 'tmap']
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)
nl = "\n" if isinstance(x, str) else b"\n"
pre, sep, post = x.rpartition(nl)
if sep:
tqdm.write(type(nl)().join(self._buf) + pre,
file=self._wrapped, nolock=nolock)
self._buf = [post]
else:
self._buf.append(x)
def builtin_iterable(func):