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)
我可以通过将输出存储在变量中来获取事实后的输出,但我似乎无法获得实时输出。我实际上想给它长时间运行的进程,因此最好在发生时查看输出(以及保存它)。这很难做到吗,还是我在这里错过了一些非常基本的东西?
command函数中的参数就是client.containers.run您要查找的内容。\n它甚至可能需要命令列表,doc(链接):
\n\ncommand (str 或 list) \xe2\x80\x93 要在容器中运行的命令。
\n
因此,只需替换command = "/bin/bash"为bash -c "echo $(find /)".
如果您想让 docker 容器保持活动状态并一一执行命令 - 创建分离的容器并只需使用exec_run:
container = client.containers.run(image=\'ubuntu\', auto_remove=False, stdin_open=True, detach=True)\ncontainer.exec_run(cmd=\'echo $(find /)\')\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
3671 次 |
| 最近记录: |