question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to get exit code of command from exec_run(stream=True)?

See original GitHub issue

As the title says, how can I get the exit code of a command when using exec_run() with stream=True?

  result = container.exec_run(cmd, stream=True, **kwargs)
  for line in result.output:
    sys.stdout.buffer.write(b'  ')
    sys.stdout.buffer.write(line)

  print(result)  # exit_code is None

Thank you

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
TomasTomecekcommented, Apr 14, 2018

Exit code should be in this metadata:

  def inspect(self):
    return self.client.api.exec_inspect(self.id)
2reactions
NiklasRosensteincommented, Apr 7, 2018

I found a workaround. Maybe this or similar functionality could be added to the ExitResult returned by Container.exec_run()?

# tools.py
import sys


def container_exec(container, cmd, stdout=True, stderr=True, stdin=False,
                   tty=False, privileged=False, user='', detach=False,
                   stream=False, socket=False, environment=None, workdir=None):
  """
  An enhanced version of #docker.Container.exec_run() which returns an object
  that can be properly inspected for the status of the executed commands.
  """

  exec_id = container.client.api.exec_create(
    container.id, cmd, stdout=stdout, stderr=stderr, stdin=stdin, tty=tty,
    privileged=privileged, user=user, environment=environment,
    workdir=workdir)['Id']

  output = container.client.api.exec_start(
    exec_id, detach=detach, tty=tty, stream=stream, socket=socket)

  return ContainerExec(container.client, exec_id, output)


class ContainerExec(object):

  def __init__(self, client, id, output):
    self.client = client
    self.id = id
    self.output = output

  def inspect(self):
    return self.client.api.exec_inspect(self.id)

  def poll(self):
    return self.inspect()['ExitCode']

  def communicate(self, line_prefix=b''):
    for data in self.output:
      if not data: continue
      offset = 0
      while offset < len(data):
        sys.stdout.buffer.write(line_prefix)
        nl = data.find(b'\n', offset)
        if nl >= 0:
          slice = data[offset:nl+1]
          offset = nl+1
        else:
          slice = data[offset:]
          offset += len(slice)
        sys.stdout.buffer.write(slice)
      sys.stdout.flush()
    while self.poll() is None:
      raise RuntimeError('Hm could that really happen?')
    return self.poll()

Usage example

  result = tools.container_exec(container, cmd, stream=True, **kwargs)
  res = result.communicate(line_prefix=b'--> ')
  if res != 0:
    error('exit code {!r}'.format(res))
Read more comments on GitHub >

github_iconTop Results From Across the Web

Bash get exit code of command on a Linux / Unix - nixCraft
Bash get exit code of command - Learn how to get the exit code of command using $? in Linux or Unix shell...
Read more >
Containers — Docker SDK for Python 6.0.1 documentation
Block until the container stops, then return its exit code. Similar to the docker wait command. Parameters. timeout (int) – Request timeout.
Read more >
Get exit code from command "exec" - Unix Stack Exchange
The only way that exec's exit status can be interpreted by the line following exec is if the exec calls fails, normally only...
Read more >
Ubuntu Manpage: docker-container-exec - Run a command in ...
docker-container-exec - Run a command in a running container ... The exit code from docker exec gives information about why the container failed...
Read more >
Bash command line exit codes demystified | Enable Sysadmin
When you execute a command or run a script, you receive an exit code. An exit code is a system response that reports...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found