4

I am trying to run commands on a container like below:

# container started
container = PythonDockerAPIs.runContainerWithoutLogs(alpineImage, 'tail -f /dev/null', detach=True)
#execute the command
cmd1 = container.exec_run('ls -ltr',stream=True, detach=True)

Is there a way to attach the logs using attach(**kwargs) to this container and print the logs later on?

https://docker-py.readthedocs.io/en/stable/containers.html

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
user2511126
  • 620
  • 1
  • 14
  • 31

1 Answers1

1

**kwargs just means the parameters listed are "keyword arguments", so for the attach function, it takes in these parameters (or "arguments") in any order using the form keyword=value:

  • stdout (bool) – Include stdout.
  • stderr (bool) – Include stderr.
  • stream (bool) – Return container output progressively as an iterator of strings, rather than a single string.
  • logs (bool) – Include the container’s previous output.

To call this function, you would do:

logs = container.attach(stdout=True, stderr=True, stream=True, logs=True)

Note that the documentation also states the logs function is a wrapper around the attach function, so you could use that function instead of attach.

Edit:

Complete usage example:

import docker
client = docker.from_env()
container = client.containers.run('hello-world', detach=True)

# method 1
print(container.logs())

# method 2
logs = container.attach(stdout=True, stderr=True, stream=False, logs=True)
print(logs)
Kyle Falconer
  • 8,302
  • 6
  • 48
  • 68
  • I tried this and when I print logs and I see this error – user2511126 Mar 07 '19 at 23:37
  • @user2511126 the documentation says if `stream=True`, the return value is an iterator of output strings, so you would need to iterate over the output, or set `stream=False`, or you could use the alternate function: [logs](https://docker-py.readthedocs.io/en/stable/containers.html#docker.models.containers.Container.logs) – Kyle Falconer Mar 07 '19 at 23:40
  • for line in logs: print "-"+line I tried this but it prints nothing and hangs forever.. – user2511126 Mar 07 '19 at 23:53
  • @user2511126 see my edit. I think the logs statement should come after you start the container, that way you have at least some log content. – Kyle Falconer Mar 07 '19 at 23:56
  • I tried exactly that and the logs are empty when I print. (both methods) – user2511126 Mar 07 '19 at 23:59
  • @user2511126 I'm not sure what you're doing with the `runContainerWithoutLogs` function in your original question, but I just tried what I put (see second edit) in the Python REPL and it's working in Python 3. – Kyle Falconer Mar 08 '19 at 00:27
  • hang on.. you have not used "exec_run" if you use exec_run with detach=true you wouldnt be able to print logs – user2511126 Mar 08 '19 at 10:45
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/189670/discussion-between-user2511126-and-kyle-falconer). – user2511126 Mar 08 '19 at 11:11