duanqiu9104 2014-08-13 10:17
浏览 147
已采纳

为cmd exec进行常规处理,但出现错误代码

I am a beginner in Go.

I would like to use the code snippet from : How would you define a pool of goroutines to be executed at once in Golang? (this answer)

I need to check the error for each cmd executed as in :

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

But, in the snippet there is no error checking:

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

How can check for errors when the cmd executes ?

  • 写回答

2条回答 默认 最新

  • duanliusong6395 2014-08-13 10:45
    关注

    That line:

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

    is adding a Cmd object into the channel, from where it will be pulled later and executed by this code:

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

    so it is here that you need to check the error code. Since you suggested you wanted to use Cmd.Output instead of Run, it would look like this:

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

    You see, exec.Command creates and initializes an object, and .Output or .Run tells that object to do its stuff.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?