Consider this issue.py
file:
JavaScript
x
6
1
import subprocess
2
3
print('Calling subprocess...')
4
subprocess.run(['python', '--version'])
5
print('Subprocess is done!')
6
Executing python issue.py
manually yields what I expect:
JavaScript
1
4
1
Calling subprocess
2
Python 3.9.0
3
Subprocess is done!
4
However, if I execute this inside a Docker container, something weird happens:
JavaScript
1
5
1
$ docker run --rm -v $(pwd):/issue python:3.9.0 python /issue/issue.py
2
Python 3.9.0
3
Calling subprocess
4
Subprocess is done!
5
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 usesFROM python
. - Using
capture_output=True
in thesubprocess.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 tostdout
(unlikepython --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
1
2
1
docker run --rm -e PYTHONUNBUFFERED=1 -v $(pwd):/issue python:3.9.0 python /issue/issue.py
2