brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python -u shows print output right away in Docker and pipes

Python
~/tips/tip-python-u-unbuffered-output

python3 -u worker.py | tee worker.log

Stop print output from showing up late, or not at all, in containers and pipes.

A Python script in a container that prints nothing for minutes and then dumps everything at once is almost always output buffering. Running Python with -u fixes it.

python3 -u worker.py | tee worker.log

# or in a Dockerfile / compose file
ENV PYTHONUNBUFFERED=1

When stdout goes to a terminal, Python flushes after every line. When it goes to a pipe, a file or docker logs, it collects output in a buffer and writes it in big blocks. That’s efficient, but it means a progress message can sit in memory long after it was printed, and if the process gets killed it may never appear.

-u switches the buffering off for stdout and stderr. The environment variable PYTHONUNBUFFERED with any non empty value does the same, which is why you see it in so many Dockerfiles.

For a single important line you can also use print(..., flush=True) and leave the rest buffered.

It does make lots of tiny writes, so a script that prints thousands of lines per second gets a bit slower. For workers and services that log now and then, I see no reason to leave it off.

Further reading: python -u, PYTHONUNBUFFERED

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link