我在 Python 中使用 tqdm 来显示控制台进度条。
我有一个来自另一个库的函数,它偶尔会写入 tqdm 循环内的 stdout 和 stderr。我无法破解该函数的源代码。
While this doc https://github.com/tqdm/tqdm#redirecting-writing显示如何重定向 sys.stdout,它不容易推广到 stderr,因为我只能将 stdout 或 stderr 之一传递给file=
tqdm 中的参数__init__
。请参阅这个问题 https://stackoverflow.com/questions/36986929/redirect-print-command-in-python-script-through-tqdm-write和它的接受的答案 https://stackoverflow.com/a/37243211/3453033用于说明问题的最少代码。
我如何重定向bothstdout 和 stderr 在一起吗?
Python在标准库中为你提供了一些帮助器,查看contextlib https://docs.python.org/3/library/contextlib.html:
>>> import io, sys
>>> from contextlib import redirect_stdout, redirect_stderr
>>> from tqdm import tqdm
>>> def foo():
... print('spam to stdout')
... print('spam to stderr', file=sys.stderr)
...
>>> out = io.StringIO()
>>> err = io.StringIO()
>>> with redirect_stdout(out), redirect_stderr(err):
... for x in tqdm(range(3), file=sys.__stdout__):
... print(x) # more spam
... foo()
...
100%|██████████| 3/3 [00:00<00:00, 29330.80it/s]
>>> out.getvalue()
'0\nspam to stdout\n1\nspam to stdout\n2\nspam to stdout\n'
>>> err.getvalue()
'spam to stderr\nspam to stderr\nspam to stderr\n'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)