【发布时间】:2016-10-25 19:02:00
【问题描述】:
总的来说,我对Golang 很陌生,我正在尝试执行bash command with its arguments n times,然后将Output 存储在一个变量中,然后将Print 存储在其中。
我可以只做一次,或者只使用loops,如下所示:
package main
import (
"fmt"
"os/exec"
"os"
"sync"
)
func main() {
//Default Output
var (
cmdOut []byte
err error
)
//Bash Command
cmd := "./myCmd"
//Arguments to get passed to the command
args := []string{"arg1", "arg2", "arg3"}
//Execute the Command
if cmdOut, err = exec.Command(cmd, args...).Output(); err != nil {
fmt.Fprintln(os.Stderr, "There was an error running "+cmd+" "+args[0]+args[1]+args[2], err)
os.Exit(1)
}
//Store it
sha := string(cmdOut)
//Print it
fmt.Println(sha)
}
这很好用,我可以轻松阅读output。
现在,我想使用 goroutines 重复同样的操作 n 次。
我尝试采用与回答 How would you define a pool of goroutines to be executed at once in Golang? 的人完全相同的方法,但我无法使其发挥作用。
这就是我到目前为止所尝试的:
package main
import (
"fmt"
"os/exec"
"sync"
)
func main() {
//Bash Command
cmd := "./myCmd"
//Arguments to get passed to the command
args := []string{"arg1", "arg2", "arg3"}
//Common Channel for the goroutines
tasks := make(chan *exec.Cmd, 64)
//Spawning 4 goroutines
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
for cmd := range tasks {
cmd.Run()
}
wg.Done()
}()
}
//Generate Tasks
for i := 0; i < 10; i++ {
tasks <- exec.Command(cmd, args...)
//Here I should somehow print the result of the latter command
}
close(tasks)
// wait for the workers to finish
wg.Wait()
fmt.Println("Done")
}
但是,我真的不知道如何存储执行命令的i-result 并打印它。
我怎样才能做到这一点?
在此先感谢,如果您对问题有任何澄清,请发表评论。
【问题讨论】: