Last active
October 15, 2020 00:42
-
-
Save lotusirous/d7a6739491577658ba4a46735de058d2 to your computer and use it in GitHub Desktop.
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" | |
| "fmt" | |
| "io" | |
| "log" | |
| "os/exec" | |
| "strings" | |
| ) | |
| func cmdChan(bin string, args ...string) (<-chan string, error) { | |
| c := make(chan string) | |
| pr, pw := io.Pipe() | |
| defer pw.Close() | |
| cmd := exec.Command(bin, args...) | |
| cmd.Stdout = pw | |
| go func() { | |
| defer pr.Close() | |
| defer close(c) // sender must close the channel | |
| rd := bufio.NewReader(pr) | |
| for { | |
| line, err := rd.ReadString('\n') | |
| if err != nil { | |
| return | |
| } | |
| line = strings.TrimRight(line, "\n") | |
| if line != "" { | |
| c <- line | |
| } | |
| } | |
| }() | |
| if err := cmd.Run(); err != nil { | |
| return nil, err | |
| } | |
| return c, nil | |
| } | |
| func main() { | |
| c, err := cmdChan("ls", "-alh") | |
| if err != nil { | |
| log.Fatalln("make line chan failed:", err) | |
| } | |
| for line := range c { | |
| fmt.Println(line) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment