client.build
返回docker
发出docker build
命令时输出的消息。您最初的错误是没有捕获响应:
response = cl.build(fileobj=f, rm = True, tag='myv/v')
如果成功,则内容看起来与通过命令行执行时一样:
list(response)
b'{"stream":" ---\\u003e bb44cb7f2d89\\n"}\r\n',
# snipped for brevity
b'{"stream":"Successfully built 6bc18019ddb6\\n"}\r\n']
在错误情况下,例如,使用愚蠢的 dockerfile:
# a dockerfile with a type in 'MAINTAINER'
f = BytesIO('''
# Shared Volume
FROM busybox:buildroot-2014.02
MAINTAIER first last, first.last@yourdomain.com
VOLUME /data
CMD ["/bin/sh"]
'''.encode('utf-8'))
中包含的输出response
如下所示:
[b'{"stream":"Step 1 : FROM busybox:buildroot-2014.02\\n"}\r\n',
b'{"stream":" ---\\u003e 9875fb006e07\\n"}\r\n',
b'{"stream":"Step 2 : MAINTAIER \\n"}\r\n',
b'{"errorDetail":{"message":"Unknown instruction: MAINTAIER"},"error":"Unknown instruction: MAINTAIER"}\r\n']
如您所见,key
其中errorDetail
包含错误消息。
因此,您可以使用字节字符串搜索来检查:
class DockerBuildException(BaseException): pass
try:
responce = self.client.build(path=self.arguments.projectPath, pull=True, rm=False, tag=self.arguments.dockerImageTag)
for i in respone:
if b'errorDetail' in i:
raise DockerBuildException("Build Failed")
except DockerBuildException as e:
print("Error: " + e.args[0])
raise
或者,更好的是,通过将每个条目转换为dict
withast.literal_eval
并使用提供的消息通知用户:
from ast import literal_eval
try:
responce = self.client.build(path=self.arguments.projectPath, pull=True, rm=False, tag=self.arguments.dockerImageTag)
for i in respone:
if b'errorDetail' in i:
d = literal_eval(i.decode('ascii')
raise DockerBuildException(d['errorDetail']['message'])
except DockerBuildException as e:
print("Error: " + e.args[0])
raise