CKTIS / Python
`sys.stdout` and the `sys` module: choosing an output stream
Import `sys` to pass the current standard output stream explicitly to `print()`, or choose another text stream for just one call.
Version: Python 3.12
Syntax
import sys
print(value, file=sys.stdout)
print(value, file=text_stream)
sys.stdout.write(text)The distinction between sys.stdout and module sys is that sys is a built-in module exposing interpreter settings and functions, while stdout is one of its attributes. import sys binds the name sys to the module in the current scope. The dot in sys.stdout reads the attribute that holds the current standard text output stream. sys.stderr is a separate stream for diagnostics.
If you omit file or pass file=None, print() uses the current sys.stdout. print(value, file=sys.stdout) explicitly selects that same stream, but it does not force output to a terminal: standard output may be redirected to a file or pipe. Passing a different stream changes the destination for that call only, without replacing sys.stdout.
Pass an object with a write() method that accepts str, not a path or a binary file. sys.stdout.write(text) writes text without adding a newline; print() adds one by default. Use flush=True if print() should flush the stream immediately.
Do not close sys.stdout just because you used it. The environment can replace it with another object, and in some setups it can be None. Do not assume that calling sys.stdout.write() directly is always possible.
Examples
import sys
from io import StringIO
print("Default")
print("Explicit", file=sys.stdout)
with StringIO() as capture:
print("Captured", file=capture)
print(capture.getvalue(), end="", file=sys.stdout)
Result
Default Explicit Captured
`Default` and `Explicit` go to the same standard output stream. `Captured` first goes into memory (`StringIO`) and appears on standard output only when the result of `getvalue()` is printed. `end=""` avoids adding a second newline.
Related lessons
- Python · Lesson 24 · Intermediate · Version: 3