Skip to content
Advertisement

How to prevent Docker from messing with subprocess output order? (MCVE included)

Consider this issue.py file:

JavaScript

Executing python issue.py manually yields what I expect:

JavaScript

However, if I execute this inside a Docker container, something weird happens:

JavaScript

How can I fix this, to make Docker respect the correct output order?

Notes:

  • This problem also happens with stderr, although the above MCVE does not show it.
  • The MCVE uses the python image directly but in my real use case I have a custom image from a custom Dockerfile which uses FROM python.
  • Using capture_output=True in the subprocess.run call and then printing the captured output is not an option for me because my real use case invokes a subprocess that prints information over time to stdout (unlike python --version) and I cannot wait for it to complete to print the entire output only after that.

Advertisement

Answer

As @DavidMaze pointed out in a comment, I just needed to set the PYTHONUNBUFFERED environment variable to 1. This can be done for example with:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement