gpt4 book ai didi

Go Routine for cmd exec 但有错误代码

转载 作者:IT王子 更新时间:2023-10-29 02:17:01 29 4
gpt4 key购买 nike

我是围棋初学者。

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

我需要检查每个执行的 cmd 的错误:

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

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

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

cmd执行时如何检查错误?

最佳答案

那一行:

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

正在将一个 Cmd 对象添加到 channel 中,之后它将被拉出并由以下代码执行:

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

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

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

你看,exec.Command 创建并初始化一个对象,.Output.Run 告诉该对象执行它的操作。

关于Go Routine for cmd exec 但有错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25283600/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com