首页 > 解决方案 > 尝试在 golang 中使用 exec.Command() 执行 docker pull 时,我没有看到进度条

问题描述

我正在使用 Go exec 包执行docker pull debian命令:

import (
    "bufio"
    "os/exec"
    "strings"
)

func main() {
    cmd := exec.Command("docker", "pull", "debian")
    stdout, _ := cmd.StdoutPipe()
    cmd.Start()
    scanner := bufio.NewScanner(stdout)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
    return nil
}

但它从来没有向我显示进度条。它仅在完全完成时显示更新。对于超过 GB 的较大图像,很难看出是否有进展。这就是它所显示的:

e9afc4f90ab0: Pulling fs layer
e9afc4f90ab0: Verifying Checksum
e9afc4f90ab0: Download complete
e9afc4f90ab0: Pull complete

是否可以获得类似于我docker pull debian在终端中运行时看到的输出或可以用来显示进度的输出?:

e9afc4f90ab0: Downloading [==========>                                        ]  10.73MB/50.39MB

标签: dockergo

解决方案


正如大卫提到的,您宁愿使用官方的 docker 引擎 SDK与 docker 交互。

初始化 docker 客户端

cli, _ := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())

拉取图片

reader, _ := cli.ImagePull(context.Background(), "hello-world", types.ImagePullOptions{})

解析json流

id, isTerm := term.GetFdInfo(os.Stdout)
_ = jsonmessage.DisplayJSONMessagesStream(reader, os.Stdout, id, isTerm, nil)

当您执行docker pull hello-world时,您将获得与 docker cli 提供的相同输出


推荐阅读