Skip to content

Instantly share code, notes, and snippets.

@klingtnet
Last active April 27, 2020 12:47
Show Gist options
  • Save klingtnet/e1991c441acca003832c6a82f95d170e to your computer and use it in GitHub Desktop.
Save klingtnet/e1991c441acca003832c6a82f95d170e to your computer and use it in GitHub Desktop.
Prefix the output of a subprocess
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"os/exec"
"golang.org/x/sync/errgroup"
)
func main() {
g, gCtx := errgroup.WithContext(context.TODO())
prefixes := []string{"foo", "bar", "baz"}
for idx := range prefixes {
prefix := prefixes[idx]
g.Go(func() error {
pr, pw := io.Pipe()
cmd := exec.CommandContext(gCtx, "sh", "-c", `head -c16 /dev/urandom | base64`)
cmd.Stdout = pw
cmd.Stderr = pw
go cmd.Run()
scanner := bufio.NewScanner(pr)
for scanner.Scan() {
fmt.Fprintf(os.Stdout, "[%s] %s\n", prefix, scanner.Text())
}
return scanner.Err()
})
}
g.Wait()
}
// https://play.golang.org/p/V1oE4Jh2fHB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment