I want to be able to seamlessly print the output from an unknown(user defined) command in go passed through a io.ReadCloser. The bufio.NewScanner reads the std out and prints the text correctly, however the color that the child process prints is not recorded and passed through the pipe(or I don't know how to access it).
I tried using execErr := syscall.Exec(binary, cmd.Args, os.Environ())
however since this takes over the go process, I can't get an array of processes to run.
// SpawnGroup spawns a group of processes
func SpawnGroup(cmds []*exec.Cmd) {
spawnWg := &sync.WaitGroup{}
spawnWg.Add(len(cmds))
defer spawnWg.Wait()
for _, cmd := range cmds {
go Spawn(cmd, spawnWg)
}
}
// Spawn spawn a child process
func Spawn(cmd *exec.Cmd, wg *sync.WaitGroup) {
defer wg.Done()
stdout, _ := cmd.StdoutPipe()
stderr, _ := cmd.StderrPipe()
err := cmd.Start()
if err != nil {
color.Red(err.Error())
}
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
errScanner := bufio.NewScanner(stderr)
for errScanner.Scan() {
color.Red(scanner.Text())
}
cmd.Wait()
}
For example, if I try to run two commands passed in an array such as sls offline
and vue-cli-service serve
everything works as expected, but the logged output doesn't have the color. Both of these processes print some of their output to the command line with color. The exact array of commands will be unknown, so I need a way to print the exact output from them.
I was able to get this to work in node by using:
let cmd = await spawn(command, args, {
stdio: 'inherit',
shell: true,
...options
});
I haven't been able to track down how to do this in go.
Thanks for any advice or help, this is my first real dive into go, but it seems like an excellent language!