docker-py icon indicating copy to clipboard operation
docker-py copied to clipboard

Get live stdout of a running container

Open francoisihry opened this issue 5 years ago • 3 comments

Hi,

I need to run a long time command in a container and print the stdout/stderr in live.

From what I have done so far I have to wait the end of the execution before being able to see the output logs.

For example, in the above code, I would like to be able to see "hello" before waiting the end of the 20secs:

import docker
client = docker.from_env()
container = client.containers.run('python:alpine', '''python -c "
                                import time; 
                                print('hello'); 
                                time.sleep(20); 
                                print('OK')"''',
                               detach=True, remove=True)

Many thanks for your help.

francoisihry avatar Nov 09 '20 14:11 francoisihry

I would also like to know how to get the live output

toxicrecker avatar Feb 08 '21 02:02 toxicrecker

Hi @francoisihry @afshin2020 @toxicrecker

The container output is available by the attach method.

>>> import docker
>>> client = docker.from_env()
>>> container = client.containers.run('python:alpine', '''python -c "import time; print('hello'); time.sleep(20); print('OK')"''', detach=True, remove=True)
>>> output = container.attach(stdout=True, stream=True, logs=True)
>>> for line in output:
>>>     print(line) 
b'hello\nOK\n'

However, to be able to "see" the hello string, the code needs to change a little bit because the function print usually is buffered, and that would cause the "delay".

You can get the hello string right away if flush parameter is True like that:

>>> import docker
>>> client = docker.from_env()
>>> container = client.containers.run('python:alpine', '''python -c "import time; print('hello', flush=True); time.sleep(5); print('OK')"''', detach=True, remove=True)
>>> output = container.attach(stdout=True, stream=True, logs=True);
>>> for line in output:
>>>     print(line)
b'hello\n'
b'OK\n'

Have a nice day :)

feliperuhland avatar Mar 26 '21 22:03 feliperuhland

Hi, @feliperuhland, I've tried to get container output as you said, but I can't get anything. I need to get container stdout when the container is already exited, so I haven't set stream=True. I've checked - container has the result in output, but I got empty string with container.attach(stdout=True, logs=True)

Drvmnekta avatar Apr 21 '24 22:04 Drvmnekta