Last active
April 27, 2020 12:47
-
-
Save klingtnet/e1991c441acca003832c6a82f95d170e to your computer and use it in GitHub Desktop.
Prefix the output of a subprocess
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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