我对Golang
比较新,在尝试执行一个带有参数的bash命令n次
,然后将输出
存储在变量中并进行打印
。
我可以只执行一次,或者像下面这样使用循环
:
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)
}
这个很好用,我能轻松地阅读输出。
现在,我想使用 goroutines
重复执行 n
次这个操作。
我尝试了遵循回答如何定义一个一次性在 Golang 中执行的 goroutine 池?的人的方法,但我无法让它工作。
到目前为止,这是我尝试过的:
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并将其打印出来。
我该如何做到这一点?
提前感谢您对问题的任何解释,如果需要进一步澄清,请留下评论。
Go
进行“并行”操作最具成本效益的方法吗?我需要对大约1,000,000
个不同的a [0]
参数执行此操作,并将结果存储在file
或db
(例如MongoDB)中。 - AndreaM16