Get live stdout of a running container
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.
I would also like to know how to get the live output
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 :)
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)