【问题标题】:How would you get the output of a command as it's running when exec-ing in Go?在 Go 中执行时,您将如何获得正在运行的命令的输出?
【发布时间】:2014-08-08 13:57:04
【问题描述】:

到目前为止,我已经看到了几种不同的方法,您可以通过这些方法轻松地在 go 中执行 shell 命令并生成它的输出。 但是,在程序仍在运行时会输出大量命令,例如,git clone ...

如果 git clone http://some.repo.git 使用类似的方式执行:

out, err := exec.Command("...").Output()

似乎没有任何输出,因为它显然正在运行。或者至少在我的经验中似乎是这样。有没有一种简单的方法或模式可以实现来显示正在运行的命令的实时输出?

【问题讨论】:

    标签: go command exec


    【解决方案1】:

    你可以得到一个管道连接到命令的stdout:

    cmd := exec.Command("...")
    
    pipe, err := cmd.StdoutPipe()
    

    然后启动命令:

    err := cmd.Start()
    

    并读取它的输出(每隔一段时间定期):

    b := make([]byte, 1024, 1024)
    
    n, err := pipe.Read(b)
    
    // b contains up to 1024 characters of cmd's output
    

    最后,在管道排干(管道中没有输出)的情况​​下,调用Wait 等待命令退出:

    err := cmd.Wait()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-21
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      • 1970-01-01
      • 2021-07-10
      相关资源
      最近更新 更多