使用python tqdm库重定向stdout和stderr [英] Redirect both stdout and stderr with python tqdm library

查看:362
本文介绍了使用python tqdm库重定向stdout和stderr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Python中使用tqdm来显示控制台进度条.

I'm using tqdm in Python to display console progress bars.

我有另一个库中的函数,偶尔在tqdm循环中写入stdout和stderr.我无法破解该函数的源代码.

I have a function from another library that occasionally writes to both stdout and stderr inside the tqdm loop. I cannot hack the source code of that function.

此文档显示了如何重定向sys.stdout,但没有因为我只能将stdout或stderr之一传递给tqdm的__init__中的file=参数,所以很容易将其推广到stderr.请参阅此问题及其可接受的答案,以说明问题的最小代码.

While 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 this question and its accepted answer for the minimal code that illustrates the problem.

如何将 的stdout和stderr重定向在一起?

How do I redirect both stdout and stderr together?

推荐答案

Python在标准库中为您提供了一些帮助,请查看

Python provides some helpers for you in the standard libraries, look in 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库重定向stdout和stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆