client.build
返回發出docker build
命令時由docker
輸出的消息。您最初的錯誤是不捕獲響應:
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, [email protected]
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']
正如您所看到的,包含errorDetail
的key
包含錯誤消息。
所以,你可以檢查的是,無論是用字節的字符串搜索:
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
與ast.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
我還沒試過,但至今非常感謝你的解釋如此之好。 –