为执行的过程创建等待/忙碌指示器 [英] Creating waiting/busy indicator for executed process

查看:70
本文介绍了为执行的过程创建等待/忙碌指示器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有执行子进程的程序,例如

i've program which execute child process like

cmd := exec.Command("npm", "install")
log.Printf("Running command and waiting for it to finish...")
err := cmd.Run()
log.Printf("Command finished with error: %v", err)

此命令正在运行时,下载并安装npm软件包会花费一些时间10到40秒,并且用户直到看到标准输出时才知道会发生什么情况(10-40秒取决于网络),我可以使用某些东西来向cli打印一些内容,以便更清楚地了解发生了什么,

While this command is running it download and install npm packages which take some time between 10 to 40 sec, and the user doesnt know what happen until he see the stdout (10-40 sec depend on the network) , there is something that I can use which prints something to the cli to make it more clear that something happen, some busy indicator(any type) until the stdout is printed to the cli ?

推荐答案

您可以使用另一个goroutine来打印一些内容(像点一样)定期(例如每秒)。命令完成后,发出信号告知goroutine终止。

You may use another goroutine to print something (like a dot) periodically, like in every second. When the command completes, signal that goroutine to terminate.

类似于以下内容:

func indicator(shutdownCh <-chan struct{}) {
    ticker := time.NewTicker(time.Second)
    defer ticker.Stop()
    for {
        select {
        case <-ticker.C:
            fmt.Print(".")
        case <-shutdownCh:
            return
        }
    }
}

func main() {
    cmd := exec.Command("npm", "install")
    log.Printf("Running command and waiting for it to finish...")

    // Start indicator:
    shutdownCh := make(chan struct{})
    go indicator(shutdownCh)

    err := cmd.Run()

    close(shutdownCh) // Signal indicator() to terminate

    fmt.Println()
    log.Printf("Command finished with error: %v", err)
}

如果您想每隔5个点重新开始一行,就这样可以做到:

If you want to start a new line after every 5 dots, this is how it can be done:

func indicator(shutdownCh <-chan struct{}) {
    ticker := time.NewTicker(time.Second)
    defer ticker.Stop()
    for i := 0; ; {
        select {
        case <-ticker.C:
            fmt.Print(".")
            if i++; i%5 == 0 {
                fmt.Println()
            }
        case <-shutdownCh:
            return
        }
    }
}

这篇关于为执行的过程创建等待/忙碌指示器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆