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
Go按行读取数据的坑
ma6174/blog#10
---捕获错误
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text()) // Println will add back the final '\n'
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
--在调用Scan之前设置buffer的大小,比如
scanner.Buffer([]byte{}, bufio.MaxScanTokenSize*10)