Docker-py:是否可以将回调函数传递给以“分离”模式运行的容器?

问题描述

我在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.

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...