Created
December 18, 2016 18:50
-
-
Save andboson/ab06eda41aeae4ef797c469d85e0941d to your computer and use it in GitHub Desktop.
catch_cmd_output
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 ( | |
"io" | |
"os" | |
"log" | |
"os/exec" | |
) | |
func main() { | |
pr, pw := io.Pipe() | |
defer pw.Close() | |
// tell the command to write to our pipe | |
cmd := exec.Command("pwd", "lh") | |
cmd.Stdout = pw | |
go func() { | |
defer pr.Close() | |
// copy the data written to the PipeReader via the cmd to stdout | |
if _, err := io.Copy(os.Stdout, pr); err != nil { | |
log.Fatal(err) | |
} | |
}() | |
// run the command, which writes all output to the PipeWriter | |
// which then ends up in the PipeReader | |
if err := cmd.Run(); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment