Created
July 1, 2017 14:37
-
-
Save virtualsafety/4b02cc6fd595646cf69784a042988095 to your computer and use it in GitHub Desktop.
read exec output line by line
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
(1)方法一 | |
cmd := exec.Command("cmd", "args") | |
stdout, err := cmd.StdoutPipe() | |
cmd.Start() | |
r := bufio.NewReader(stdout) | |
for { | |
line, isPrefix, err := r.ReadLine() | |
fmt.Printf("line %v / prefix %v / err %v\n", string(line), isPrefix, err) | |
if err == io.EOF { | |
break | |
} | |
time.Sleep(1 * time.Second) | |
} | |
http://golang-examples.tumblr.com/post/41864592909/read-stdout-of-subprocess | |
(2)方法二 | |
stdout, err := cmd.StdoutPipe() | |
if err != nil { | |
return 0, err | |
} | |
// start the command after having set up the pipe | |
if err := cmd.Start(); err != nil { | |
return 0, err | |
} | |
// read command's stdout line by line | |
in := bufio.NewScanner(stdout) | |
for in.Scan() { | |
log.Printf(in.Text()) // write each line to your log, or anything you need | |
} | |
if err := in.Err(); err != nil { | |
log.Printf("error: %s", err) | |
} | |
https://stackoverflow.com/questions/25190971/golang-copy-exec-output-to-log |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://mickey24.hatenablog.com/entry/bufio_scanner_line_length