Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to get STDOUT when the container exit with non-zero code? #2745

Open
jih-dk opened this issue Jan 6, 2021 · 1 comment
Open

how to get STDOUT when the container exit with non-zero code? #2745

jih-dk opened this issue Jan 6, 2021 · 1 comment

Comments

@jih-dk
Copy link

jih-dk commented Jan 6, 2021

I run a command in a container with containers.run() method, when an error happened, the container returns a non-zero code, then I can only see the contents og STDERR in ContainerError.

If I correctly understood the codes, when a container exit with non-zero code, it firstly clean the out variable, and collect all STDERR and pass it to ContainerError object.
image

I would like to see the STDOUT messages before the error happened, is there a way to do that?

@feliperuhland
Copy link
Contributor

Hi @jinxudb

If you use detach=True, you can get the stdout from the container.logs().
Otherwise, you can get from ContainerError.container.logs().
So, you have to catch the exception to get that.

>>> import docker
>>> cli = docker.from_env()
>>> cli.containers.run("python:latest", "python -c 'print(123); exit(1)'")
---------------------------------------------------------------------------
ContainerError                            Traceback (most recent call last)
<ipython-input-5-a3a922806153> in <module>
----> 1 cli.containers.run("python:latest", "python -c 'print(123); exit(1)'")

~/docker-py/docker/models/containers.py in run(self, image, command, stdout, stderr, remove, **kwargs)
    838             container.remove()
    839         if exit_status != 0:
--> 840             raise ContainerError(
    841                 container, exit_status, command, image, out
    842             )

ContainerError: Command 'python -c 'print(123); exit(1)'' in image 'python:latest' returned non-zero exit status 1: b''

>>> a = cli.containers.run("python:latest", "python -c 'print(123); exit(1)'", detach=True)
>>> a.logs()
b'123\n'

>>> try:
...     cli.containers.run("python:latest", "python -c 'print(123); exit(1)'")
... except ContainerError as exc:
...     print(exc.container.logs())
b'123\n'

I hope that helps.
Have a nice day :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants