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



Python 菜鸟 在这里,我正在尝试使用docker-py中的exec_run函数将命令发送到分离的 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()

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

我实现了这样的行为:

def install_model(self, language: str) -> bool:
if self.container:
_, stream = self.container.exec_run(
cmd=f"lima_models.py -l {language}", stream=True)
for data in stream:
print(data.decode(), end='')
print()

如您所见,我使用stream=True然后迭代结果。我打印解码的数据,但您也可以存储它以备后用。执行的命令在每个输出行的开头使用r生成进度条。这就是添加end=''参数的原因。

以下是使用上述解决方案修改的 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
_, stream = box.exec_run(cmd = "find /", stream=True)
for data in stream:
print(data.decode())
box.stop()
sys.exit()

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

命令(str 或列表(– 要在容器中运行的命令。

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


如果你想让docker容器保持活动状态并逐个执行命令 - 创建分离的容器并简单地使用exec_run

container = client.containers.run(image='ubuntu', auto_remove=False, stdin_open=True, detach=True)
container.exec_run(cmd='echo $(find /)')

最新更新