使用 python tqdm 库重定向 stdout 和 stderr
Redirect both stdout and stderr with python tqdm library
我在 Python 中使用 tqdm 来显示控制台进度条。
我有一个来自另一个库的函数,它偶尔会在 tqdm 循环内同时写入 stdout 和 stderr。我无法破解该函数的源代码。
虽然 this doc shows how to redirect sys.stdout, it doesn't easily generalize to stderr because I can pass only one of stdout or stderr to the file=
parameter in tqdm's __init__
. Please refer to and its 是说明问题的最少代码。
如何同时重定向 both stdout 和 stderr?
Python 在标准库中为您提供了一些帮助程序,请查看 contextlib
:
>>> 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'
我在 Python 中使用 tqdm 来显示控制台进度条。
我有一个来自另一个库的函数,它偶尔会在 tqdm 循环内同时写入 stdout 和 stderr。我无法破解该函数的源代码。
虽然 this doc shows how to redirect sys.stdout, it doesn't easily generalize to stderr because I can pass only one of stdout or stderr to the file=
parameter in tqdm's __init__
. Please refer to
如何同时重定向 both stdout 和 stderr?
Python 在标准库中为您提供了一些帮助程序,请查看 contextlib
:
>>> 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'