如何检测docker-py client.build()失败

我使用docker-py来构build和运行Docker镜像。

从阅读文档 ,我不清楚如何build立图像是否有错误。 当出现错误时, build()不会引发exception。 这让我觉得我必须调查回应的回应。

什么是确定是否docker-py的client.build()失败的最佳方法?

它看起来像“最好”的方法是解码响应,并寻找一个名为“错误”的关键。

例如:

 for response in client.build(path, tag, decode=True): if response.has_key('error'): raise Exception("Error building docker image: {}".format(response['error'])) 

创build一个StreamLineBuilder生成器:

 import json class StreamLineBuildGenerator(object): def __init__(self, json_data): self.__dict__ = json.loads(json_data) 

然后使用这个生成器来parsing你的stream:

 import docker docker_client = docker.Client(version="1.18", base_url="unix:///var/run/docker.sock") generator = docker_client.build(nocache=False, rm=True, stream=True, tag="my_image_tag", path="my_path") for line in generator: try: stream_line = StreamLineBuildGenerator(line) if hasattr(stream_line, "error"): print(stream_line.error) if hasattr(stream_line, "errorDetail"): if not stream_line.error == stream_line.errorDetail["message"]: if hasattr(stream_line.errorDetail, "code"): print("[" + stream_line.errorDetail["code"] + "] ", False) print(stream_line.errorDetail["message"]) except ValueError: # If we are not able to deserialize the received line as JSON object, just print it out print(line) continue