Обложка канала

Библиотека Python разработчика

20835 @BookPython

Библиотека Python разработчика. Книги по программированию на Python.

Библиотека Python разработчика

4 года назад
Открыть в
Some code you are using may print data you are interested in stdout instead of providing some API that is usable within a program (returning a string, for example). Instead of refactoring such code you may use the contextlib.redirect_stdout context manager that allows temporary redirecting stdout to any custom file-like object. In conjuncture with io.StringIO, it allows capturing output to a variable. from contextlib import redirect_stdout from io import StringIO s = StringIO() with redirect_stdout(s): print(42) print(s.getvalue()) There is also contextlib.redirect_stderr available for redirecting sys.stderr.