英文:
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()
}()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论