all Python 3systerm
sys.stdout
streams
The standard output stream — a text file object print() writes to by default.
Syntax
import sys
sys.stdout.write('text\n')
When output goes to a file or a pipe, sys.stdout is block-buffered and lines appear later than expected — print(..., flush=True) or sys.stdout.flush() helps. sys.stdout can be replaced by any object with a write method, such as io.StringIO, to capture output; the original stream is always available as sys.__stdout__.
Examples
import sys
n = sys.stdout.write('hello\n') # → hello
print(n) # → 6 — write возвращает число записанных символов
import io, sys
buffer = io.StringIO()
sys.stdout = buffer
print('captured')
sys.stdout = sys.__stdout__
print(repr(buffer.getvalue())) # → 'captured\n'
See also
Open in the full glossarydocs.python.orgReport an inaccuracy