docker 我怎样才能得到百分比拉码头形象?

v440hwme  于 2023-02-07  发布在  Docker
关注(0)|答案(1)|浏览(136)

它通过命令或docker-py API c.pull(repository, tag=None, stream=False)使用docker pull
如何获取此映像的拉取(下载)进度?

qvtsj1bj

qvtsj1bj1#

docker-py提供了客户端pull API,它提供了完成计数和总计数。你可以将它们相除以得到你需要的百分比。
例如,以下代码段:

import docker
client = docker.from_env()
resp = client.api.pull(image_name, stream=True, decode=True)
for line in resp:
    print(json.dumps(line, indent=4))

将打印:

{
    "status": "Downloading",
    "progressDetail": {
        "current": 12253570,
        "total": 12627702
    },
    "progress": "[================================================>  ]  12.25MB/12.63MB",
    "id": "14e6ed0b1573"
}
{
    "status": "Downloading",
    "progressDetail": {
        "current": 12384642,
        "total": 12627702
    },
    "progress": "[=================================================> ]  12.38MB/12.63MB",
    "id": "14e6ed0b1573"
}

对于每条消息,您可以获取current/total以获得所需的功能。
我写了一个程序,有丰富的库来显示进度条。它可以单独打印每一层的进度(包括如果是下载还是提取那一层)。

import docker
from rich.progress import Progress

tasks = {}

# Show task progress (red for download, green for extract)
def show_progress(line, progress):
    if line['status'] == 'Downloading':
        id = f'[red][Download {line["id"]}]'
    elif line['status'] == 'Extracting':
        id = f'[green][Extract  {line["id"]}]'
    else:
        # skip other statuses
        return

    if id not in tasks.keys():
        tasks[id] = progress.add_task(f"{id}", total=line['progressDetail']['total'])
    else:
        progress.update(tasks[id], completed=line['progressDetail']['current'])

def image_pull(image_name):
    print(f'Pulling image: {image_name}')
    with Progress() as progress:
        client = docker.from_env()
        resp = client.api.pull(image_name, stream=True, decode=True)
        for line in resp:
            show_progress(line, progress)

if __name__ == '__main__':
    # Pull a large image
    IMAGE_NAME = 'bitnami/pytorch'
    image_pull(IMAGE_NAME)

输出结果如下图所示,下载状态显示为红色,解压状态显示为绿色。
Python program to show docker image pull progress bar

相关问题