我正在 Python 中使用docker-py运行一个容器。与文档类似:
import docker
client = docker.from_env()
container = client.containers.run('bfirsh/reticulate-splines', detach=True)
Run Code Online (Sandbox Code Playgroud)
容器执行一些任务并将.json文件保存到共享卷。一切工作正常,除了我不知道如何在后台运行时捕获容器退出。更具体地说,我的问题如下:
“docker-py 有没有办法将回调函数传递给以分离模式运行的容器?”
我想访问.json 退出时保存的内容,并避免使用丑陋的语句,例如time.sleep()或 在status is running. 从文档来看,这似乎不可能。您有什么解决方法可以分享吗?
回答我自己的问题,我采用了以下使用线程的解决方案。
import docker
import threading
def run_docker():
""" This function run a Docker container in detached mode and waits for completion.
Afterwards, it performs some tasks based on container's result.
"""
docker_client = docker.from_env()
container = docker_client.containers.run(image='bfirsh/reticulate-splines', detach=True)
result = container.wait()
container.remove()
if result['StatusCode'] == 0:
do_something() # For example access and save container's log in a json file
else:
print('Error. Container exited with status code', result['StatusCode'])
def main():
""" This function start a thread to run the docker container and
immediately performs other tasks, while the thread runs in background.
"""
threading.Thread(target=run_docker, name='run-docker').start()
# Perform other tasks while the thread is running.
Run Code Online (Sandbox Code Playgroud)