您如何在Go中获得“实时”控制台输出? [重复]

This question already has an answer here:


What is the equivalent of this in Golang. Basically I want to be able to execute a command get it in pieces as it comes out. This is a example of what I have in Node.js at the current moment.

var exec = require('child_process').exec;
exec('ls').stdout.on('data', data => {
    console.log(data); 
});

Intention: The intention is to run a command then use websockets to ouput it live so a server.

</div>

You can have a look at here: https://golang.org/src/os/exec/example_test.go

Example of pipe stdout stream:

package main

import (
    "bufio"
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("ls")
    stdout, _ := cmd.StdoutPipe()
    cmd.Start()

    scanner := bufio.NewScanner(stdout)
    scanner.Split(bufio.ScanWords)
    for scanner.Scan() {
        m := scanner.Text()
        fmt.Println(m)
    }
    cmd.Wait()
}