Capturing output of python script run inside a docker container
You are experiencing this behavior because python buffers its outputs by default.
Take this example:
vagrant@docker:/vagrant/tmp$ cat foo.py#!/usr/bin/pythonfrom time import sleepwhile True: print "f00" sleep(1)
then observing the logs from a container running as a daemon does not show anything:
vagrant@docker:/vagrant/tmp$ docker logs -f $(docker run -d -v $(pwd):/app dockerfile/python python /app/foo.py)
but if you disable the python buffered output with the -u
command line parameter, everything shows up:
vagrant@docker:/vagrant/tmp$ docker logs -f $(docker run -d -v $(pwd):/app dockerfile/python python -u /app/foo.py)f00f00f00f00
You can also inject the PYTHONUNBUFFERED
environment variable:
vagrant@docker:/vagrant/tmp$ docker logs -f $(docker run -d -v $(pwd):/app -e PYTHONUNBUFFERED=0 dockerfile/python python /app/foo.py)f00f00f00f00
Note that this behavior affects only containers running without the -t
or --tty
parameter.
You may experience a race condition since the started container is running in parallel to your control program. You need to wait for your container to start and finish before grabbing the logs. Add a docker.wait to your code right after docker.start.
docker.wait(contid)
Your output seems empty because nothing has yet been logged.