FIELD NOTE · TA-95 REGISTER

The Staircase Problem

Why terminal progress bars leave copies of themselves behind, and how to coordinate tqdm with printing, logging, notebooks, and CI.

When print() and tqdm share a terminal, a progress bar can leave a copy of itself after every message:

Processing:  10%|█         | 10/100 [00:01<00:09]
Warning: item_10 returned None
Processing:  12%|█▏        | 12/100 [00:01<00:08]
Warning: item_20 returned None
Processing:  22%|██▏       | 22/100 [00:02<00:07]

I spent two hours blaming tqdm. The actual problem was one cursor shared by several writers on two output streams.

I checked the examples below with Python 3.13 and tqdm 4.67.1.

Why the bar moves

A text progress bar writes one line, returns the cursor to column zero, and overwrites that line. Two control characters do most of the work:

CharacterEffect
\rReturn to column zero on the current line
\nAdvance to the next line

A simplified redraw looks like this:

  1. Write [████░░░░] 40%.
  2. Write \r.
  3. Write [█████░░░] 50% over the same row.

Real libraries also clear leftover characters, track multiple rows, and respond to terminal width. They still need control of the cursor while the display is active.

tqdm writes its meter to stderr by default. Python’s print() writes to stdout. The streams are separate, but an interactive terminal puts both on the same screen. Logging, warnings, subprocesses, and concurrent workers can move the cursor between redraws.

An IDE panel or continuous integration (CI) log may be append-only or may emulate a terminal poorly. The same program can look correct in one terminal and produce a staircase elsewhere.

Use tqdm.write() for messages while the bar is active:

from time import sleep
from tqdm import tqdm

for item in tqdm(range(100), desc="Processing"):
    sleep(0.01)
    if item % 10 == 0:
        tqdm.write(f"Checkpoint {item}: processed successfully")

tqdm.write() clears the display, writes the message, and redraws the bar. It works for occasional status messages. A high-volume event stream belongs in a log file.

If the bar writes to an explicit stream, send the message there too:

import sys
from tqdm import tqdm

bar = tqdm(range(100), file=sys.stderr)
for item in bar:
    if item == 50:
        tqdm.write("Halfway", file=sys.stderr)

Redirect logging

tqdm includes a logging helper:

import logging
from tqdm import tqdm
from tqdm.contrib.logging import logging_redirect_tqdm

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

with logging_redirect_tqdm():
    for item in tqdm(range(100), desc="Processing"):
        if item % 25 == 0:
            logger.info("Processed %s items", item)

Keep normal structured logging for the application. The redirect only coordinates terminal output with the bar.

Disable bars outside a terminal

A progress bar usually adds noise to a redirected file or CI log. disable=None tells tqdm to draw only when its selected stream is a terminal:

import sys
from tqdm import tqdm

for item in tqdm(range(100), file=sys.stderr, disable=None):
    pass

Use sys.stderr.isatty() directly when the application needs to make the choice itself.

For terminals that change width, let tqdm recalculate the columns:

for item in tqdm(range(100), dynamic_ncols=True):
    pass

A fixed ncols=80 works for a known display, but it wraps on narrower terminals.

Give nested bars their own rows

from tqdm import tqdm

for epoch in tqdm(range(10), position=0, desc="Epochs"):
    for batch in tqdm(
        range(100),
        position=1,
        desc="Batches",
        leave=False,
    ):
        pass

position assigns each bar a row. This still depends on cursor movement, so disable nested bars in append-only output rather than trying to repair the log afterward.

Use the notebook renderer in notebooks

tqdm.auto selects a notebook widget when one is available and falls back to the terminal implementation elsewhere:

from tqdm.auto import tqdm

for item in tqdm(range(100)):
    pass

Use from tqdm.notebook import tqdm when the notebook widget is a hard requirement.

Use one display manager

If a command already uses Rich for tables, status displays, or multiple live regions, use its Progress API instead of mixing display libraries:

from time import sleep
from rich.progress import Progress

with Progress() as progress:
    task = progress.add_task("Processing", total=100)

    for item in range(100):
        sleep(0.01)
        if item and item % 25 == 0:
            progress.console.print(f"Processed {item} items")
        progress.advance(task)

Rich redirects standard output and error while its live display is active unless configured otherwise. Printing through progress.console makes the owner of the display explicit.

Changing libraries won’t fix uncontrolled concurrent output. Pick one component to manage the cursor and route messages through it.

Fix order

When a bar leaves copies behind:

  1. Replace loop-time print() calls with tqdm.write().
  2. Redirect logging with logging_redirect_tqdm().
  3. Check the streams used by the bar and messages.
  4. Disable bars for non-interactive output.
  5. Assign rows to nested bars.
  6. Use one live-display library at a time.

References: