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

Getting logs from exec_run in a stream fashion

Open AlexKaravaev opened this issue 3 years ago • 1 comments

What I want to do is to get stdout/stderr of the command in exec_run line after line. I tried settung stream=True and also detach=True and then after retrieving logs, but no luck. I was only abailable to retrieve logs, once command in exec_run is executed.

Below example, where logs just hang and nothing happens.

from podman import PodmanClient

with PodmanClient() as client:
    client.containers.run(
        image="ubuntu",
        name="test",
        detach=True,
    )
    cmd = "apt-get update"

    print(cmd)
    res = client.containers.list()[-1].exec_run(
        cmd,
        detach=True,
    )
    print("before")
    print(res)
    logs = client.containers.list()[-1].logs(stream=True)

    for r in logs:
        print(r.decode("UTF-8"))

If I set stream=True, then bug in https://github.com/containers/podman-py/issues/201 will happen.

Is there a way to get these logs in a streamed way until fix for https://github.com/containers/podman-py/issues/201 is ready?

AlexKaravaev avatar Oct 13 '22 14:10 AlexKaravaev

I did it like this:

        node_type="podman" if client.containers.client.user_agent.startswith("Podman") else "docker"
        command=f"{node_type} exec -it {client.containers.name} sh -c {cmd}"
        output=''
        with subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as process:
            for line in process.stdout:
                logger.debug(line.decode().rstrip("\n"))
                output=output+line.decode()
            process.wait()

Orca75 avatar Jan 17 '24 11:01 Orca75