Skip to content

Commit 7cc4851

Browse files
Clarify stdout flush behavior for newline characters in print()
This PR adds a note to the print() documentation to clarify how Python’s stdout buffering works with newline (\n) characters inside a single print call. Motivation: Current documentation mentions that flush() is implied for writes containing newlines. However, it does not explain that Python flushes only after the entire write operation, not mid-string. This can confuse users coming from C, who expect a flush at each newline, and developers writing scripts that rely on immediate output for progress indicators or CLI feedback. What’s added: A .. note:: block explaining that stdout behavior depends on the environment (TTY vs redirected stdout). Guidance on explicitly flushing with flush=True or sys.stdout.flush(). Mention of python -u for unbuffered output. A short example demonstrating the behavior. Impact: Improves clarity for learners and developers. Aligns documentation with actual behavior across different environments. Not a behavior change — documentation-only PR. Related Issue: Addresses issue #141395
1 parent 9ce99c6 commit 7cc4851

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Doc/library/functions.rst

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1607,6 +1607,31 @@ are always available. They are listed here in alphabetical order.
16071607
Output buffering is usually determined by *file*.
16081608
However, if *flush* is true, the stream is forcibly flushed.
16091609

1610+
.. note::
1611+
1612+
In Python, printing a string containing newline characters does not automatically flush stdout.
1613+
Python performs buffering at the write/operation level, so newlines inside a single write
1614+
do not necessarily trigger an immediate flush. The exact timing of output may vary depending
1615+
on the environment:
1616+
1617+
- When stdout is connected to a terminal (TTY), output is line-buffered and typically flushes
1618+
after the write completes.
1619+
- When stdout is redirected to a file or pipe, output may be fully buffered and not flush
1620+
until the buffer fills or flush is requested.
1621+
1622+
For guaranteed immediate output, use ``flush=True`` or call ``sys.stdout.flush()`` explicitly.
1623+
Running Python with the ``-u`` flag also forces unbuffered output, which may be useful in
1624+
scripts requiring immediate writes.
1625+
1626+
Example:
1627+
1628+
.. code-block:: python
1629+
1630+
from time import sleep
1631+
1632+
print("Hello\nWorld", end='') # Both lines appear together on TTY
1633+
sleep(3)
1634+
print("Hi there!")
16101635
16111636
.. versionchanged:: 3.3
16121637
Added the *flush* keyword argument.

0 commit comments

Comments
 (0)