2017-05-29 00:19:46 +00:00
|
|
|
"""Redirecting writing
|
|
|
|
|
|
|
|
If using a library that can print messages to the console, editing the library
|
|
|
|
by replacing `print()` with `tqdm.write()` may not be desirable.
|
|
|
|
In that case, redirecting `sys.stdout` to `tqdm.write()` is an option.
|
|
|
|
|
|
|
|
To redirect `sys.stdout`, create a file-like class that will write
|
|
|
|
any input string to `tqdm.write()`, and supply the arguments
|
|
|
|
`file=sys.stdout, dynamic_ncols=True`.
|
|
|
|
|
|
|
|
A reusable canonical example is given below:
|
|
|
|
"""
|
|
|
|
from __future__ import print_function
|
|
|
|
from time import sleep
|
|
|
|
import contextlib
|
|
|
|
import sys
|
|
|
|
from tqdm import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
class DummyTqdmFile(object):
|
|
|
|
"""Dummy file-like that will write to tqdm"""
|
|
|
|
file = None
|
|
|
|
|
|
|
|
def __init__(self, file):
|
|
|
|
self.file = file
|
|
|
|
|
|
|
|
def write(self, x):
|
|
|
|
# Avoid print() second call (useless \n)
|
|
|
|
if len(x.rstrip()) > 0:
|
|
|
|
tqdm.write(x, file=self.file)
|
|
|
|
|
2017-09-21 00:38:57 +00:00
|
|
|
def flush(self):
|
|
|
|
return getattr(self.file, "flush", lambda: None)()
|
|
|
|
|
2017-05-29 00:19:46 +00:00
|
|
|
|
|
|
|
@contextlib.contextmanager
|
2017-09-23 17:40:37 +00:00
|
|
|
def std_out_err_redirect_tqdm():
|
|
|
|
orig_out_err = sys.stdout, sys.stderr
|
2017-05-29 00:19:46 +00:00
|
|
|
try:
|
2017-09-23 17:40:37 +00:00
|
|
|
# sys.stdout = sys.stderr = DummyTqdmFile(orig_out_err[0])
|
|
|
|
sys.stdout, sys.stderr = map(DummyTqdmFile, orig_out_err)
|
|
|
|
yield orig_out_err[0]
|
2017-05-29 00:19:46 +00:00
|
|
|
# Relay exceptions
|
|
|
|
except Exception as exc:
|
|
|
|
raise exc
|
2017-09-23 17:40:37 +00:00
|
|
|
# Always restore sys.stdout/err if necessary
|
2017-05-29 00:19:46 +00:00
|
|
|
finally:
|
2017-09-23 17:40:37 +00:00
|
|
|
sys.stdout, sys.stderr = orig_out_err
|
2017-05-29 00:19:46 +00:00
|
|
|
|
|
|
|
|
2017-09-23 17:40:37 +00:00
|
|
|
def some_fun(i):
|
|
|
|
print("Fee, fi, fo,".split()[i])
|
2017-05-29 00:19:46 +00:00
|
|
|
|
|
|
|
|
2017-09-23 17:40:37 +00:00
|
|
|
# Redirect stdout to tqdm.write()
|
|
|
|
with std_out_err_redirect_tqdm() as orig_stdout:
|
|
|
|
# tqdm needs the original stdout
|
2017-05-29 00:19:46 +00:00
|
|
|
# and dynamic_ncols=True to autodetect console width
|
2017-09-23 17:40:37 +00:00
|
|
|
for i in tqdm(range(3), file=orig_stdout, dynamic_ncols=True):
|
2017-10-05 01:13:26 +00:00
|
|
|
# order of the following two lines should not matter
|
2017-09-23 17:40:37 +00:00
|
|
|
some_fun(i)
|
2017-10-05 01:13:26 +00:00
|
|
|
sleep(.5)
|
2017-05-29 00:19:46 +00:00
|
|
|
|
|
|
|
# After the `with`, printing is restored
|
2017-09-23 17:40:37 +00:00
|
|
|
print("Done!")
|