1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
package argv
import (
"errors"
"io"
"os"
"os/exec"
)
func Cmds(args ...[]string) ([]*exec.Cmd, error) {
var cmds []*exec.Cmd
for _, argv := range args {
if len(argv) == 0 {
return nil, errors.New("invalid cmd")
}
cmds = append(cmds, exec.Command(argv[0], argv[1:]...))
}
return cmds, nil
}
func Pipe(stdin io.Reader, stdout, stderr io.Writer, cmds ...*exec.Cmd) error {
if stdin == nil {
stdin = os.Stdin
}
if stdout == nil {
stdout = os.Stdout
}
if stderr == nil {
stderr = os.Stderr
}
l := len(cmds)
if l == 0 {
return nil
}
var err error
for i := 0; i < l; i++ {
if i == 0 {
cmds[i].Stdin = stdin
} else {
cmds[i].Stdin, err = cmds[i-1].StdoutPipe()
if stderr != nil {
break
}
}
cmds[i].Stderr = stderr
if i == l-1 {
cmds[i].Stdout = stdout
}
}
if err != nil {
return err
}
for i := range cmds {
err = cmds[i].Start()
if err != nil {
return err
}
}
for i := range cmds {
err = cmds[i].Wait()
if err != nil {
return err
}
}
return nil
}
|