doutuo3575 2018-05-22 11:54
浏览 64
已采纳

为执行的过程创建等待/忙碌指示器

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)

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 ?

  • 写回答

2条回答 默认 最新

  • doutuo8800 2018-05-22 11:59
    关注

    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.

    Something like this:

    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)
    }
    

    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
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题