登录
首页 >  Golang >  Go问答

在 golang 中使用 exec.Command() 执行 docker pull 时,未显示进度条

来源:stackoverflow

时间:2024-02-28 13:57:24 125浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《在 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

解决方案


正如 david 提到的,您宁愿使用 official docker engine 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 提供的相同的输出

今天关于《在 golang 中使用 exec.Command() 执行 docker pull 时,未显示进度条》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>