实时跟踪 docker-py 的 exec_run() 输出

drg*_*bon 5 python stdout output docker dockerpy

Python noob 这里,我尝试使用exec_runfrom 的函数docker-py将命令发送到分离的 docker 容器,并让输出实时到达 stdout。这是一个 MWE:

import docker, sys
client = docker.from_env()
# start a detached container
box = client.containers.run(image = "ubuntu",
                            remove = True,
                            detach = True,
                            tty = True,
                            command = "/bin/bash")
# send a test command
box.exec_run(cmd = "find /") # gives no output in the terminal when run

# same again, but save the output
run = box.exec_run(cmd = "find /")
print(run.output.decode("utf-8"))

box.stop()
sys.exit()
Run Code Online (Sandbox Code Playgroud)

我可以通过将输出存储在变量中来获取事实后的输出,但我似乎无法获得实时输出。我实际上想给它长时间运行的进程,因此最好在发生时查看输出(以及保存它)。这很难做到吗,还是我在这里错过了一些非常基本的东西?

Kir*_*Rud 0

command函数中的参数就是client.containers.run您要查找的内容。\n它甚至可能需要命令列表,doc(链接):

\n
\n

command (str 或 list) \xe2\x80\x93 要在容器中运行的命令。

\n
\n

因此,只需替换command = "/bin/bash"bash -c "echo $(find /)".

\n
\n

如果您想让 docker 容器保持活动状态并一一执行命令 - 创建分离的容器并只需使用exec_run

\n
container = client.containers.run(image=\'ubuntu\', auto_remove=False, stdin_open=True, detach=True)\ncontainer.exec_run(cmd=\'echo $(find /)\')\n
Run Code Online (Sandbox Code Playgroud)\n