Skip to content

Instantly share code, notes, and snippets.

@lotusirous
Last active October 15, 2020 00:42
Show Gist options
  • Select an option

  • Save lotusirous/d7a6739491577658ba4a46735de058d2 to your computer and use it in GitHub Desktop.

Select an option

Save lotusirous/d7a6739491577658ba4a46735de058d2 to your computer and use it in GitHub Desktop.
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