Go Routine for cmd exec but with errorcode

huangapple go评论98阅读模式
英文:

Go Routine for cmd exec but with errorcode

问题

我是一个Go语言的初学者。

我想使用这个代码片段:https://stackoverflow.com/questions/18405023/how-would-you-define-a-pool-of-goroutines-to-be-executed-at-once-in-golang
这个答案

我需要像这样检查每个执行的命令的错误:

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

但是,在这个代码片段中没有错误检查:

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

当命令执行时,如何检查错误?

英文:

I am a beginner in Go.

I would like to use the code snippet from : https://stackoverflow.com/questions/18405023/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 ?

答案1

得分: 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告诉该对象执行其任务。

英文:

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.

答案2

得分: 0

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

你可以在go func()中检查错误。

    go func() {
        for cmd := range tasks {
            err := cmd.Run()
            // 在这里进行测试
        }
        wg.Done()
    }()
英文:

exec.Command doesn't execute the command, it creates a *Cmd only.

You would check the err in the go func()

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

huangapple
  • 本文由 发表于 2014年8月13日 18:17:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/25283600.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定