【问题标题】:Go Routine for cmd exec but with errorcodeGo Routine for cmd exec 但有错误代码
【发布时间】:2014-08-13 10:17:48
【问题描述】:

我是围棋初学者。

我想使用来自 How would you define a pool of goroutines to be executed at once in Golang? 的代码 sn-p (this answer)

我需要检查每个执行的 cmd 的错误,如下所示:

out, err := exec.Command(cmd,params).Output()

但是,在 sn-p 中没有错误检查:

tasks <- exec.Command("zenity", "--info", "--text='Hello from iteration n."+strconv.Itoa(i)+"'")

cmd执行时如何检查错误?

【问题讨论】:

    标签: go exec


    【解决方案1】:

    那行:

    tasks <- exec.Command("zenity", "--info", "--text='Hello from iteration n."+strconv.Itoa(i)+"'")
    

    正在将Cmd 对象添加到通道中,稍后将从该通道中拉取并由以下代码执行:

        for cmd := range tasks {
            cmd.Run()
        }
    

    所以在这里您需要检查错误代码。既然你建议你想使用Cmd.Output 而不是Run,它看起来像这样:

        for cmd := range tasks {
            out, err := Cmd().Output()
        }
    

    你看,exec.Command 创建并初始化一个对象,.Output.Run 告诉该对象做它的事情。

    【讨论】:

      【解决方案2】:

      exec.Command 不执行命令,它只创建一个*Cmd

      你会检查go func()中的错误

          go func() {
              for cmd := range tasks {
                  err := cmd.Run()
                  // do the test here
              }
              wg.Done()
          }()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-02
        相关资源
        最近更新 更多