问题描述
我在Python中使用docker-py运行容器。与文档类似:
import docker
client = docker.from_env()
container = client.containers.run('bfirsh/reticulate-splines',detach=True)
容器执行一些任务,并将.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.