update redirect printing documentation

fixes #439
This commit is contained in:
Casper da Costa-Luis 2017-09-21 01:38:57 +01:00
parent da46cd4371
commit 58a4bbf104
No known key found for this signature in database
GPG Key ID: 986B408043AE090D
2 changed files with 10 additions and 6 deletions

View File

@ -657,10 +657,8 @@ A reusable canonical example is given below:
.. code:: python
from time import sleep
import contextlib
import sys
from tqdm import tqdm
class DummyTqdmFile(object):
@ -674,6 +672,9 @@ A reusable canonical example is given below:
if len(x.rstrip()) > 0:
tqdm.write(x, file=self.file)
def flush(self):
return getattr(self.file, "flush", lambda: None)()
@contextlib.contextmanager
def stdout_redirect_to_tqdm():
save_stdout = sys.stdout
@ -692,11 +693,11 @@ A reusable canonical example is given below:
# Redirect stdout to tqdm.write() (don't forget the `as save_stdout`)
with stdout_redirect_to_tqdm() as save_stdout:
# tqdm call need to specify sys.stdout, not sys.stderr (default)
# tqdm needs the original sys.stdout
# and dynamic_ncols=True to autodetect console width
for _ in tqdm(range(3), file=save_stdout, dynamic_ncols=True):
blabla()
sleep(.5)
blabla()
# After the `with`, printing is restored
print('Done!')

View File

@ -29,6 +29,9 @@ class DummyTqdmFile(object):
if len(x.rstrip()) > 0:
tqdm.write(x, file=self.file)
def flush(self):
return getattr(self.file, "flush", lambda: None)()
@contextlib.contextmanager
def stdout_redirect_to_tqdm():
@ -50,11 +53,11 @@ def blabla():
# Redirect stdout to tqdm.write() (don't forget the `as save_stdout`)
with stdout_redirect_to_tqdm() as save_stdout:
# tqdm call need to specify sys.stdout, not sys.stderr (default)
# tqdm needs the original sys.stdout
# and dynamic_ncols=True to autodetect console width
for _ in tqdm(range(3), file=save_stdout, dynamic_ncols=True):
blabla()
sleep(.5)
blabla()
# After the `with`, printing is restored
print('Done!')