How to process stderr in go?

huangapple go评论92阅读模式
英文:

How to process stderr in go?

问题

我有一个名为"myapp"的应用程序。该应用程序只是将内容写入stderr。

重要的部分是,我想要捕获stderr中写入的内容,并实时处理它。我该如何做到这一点?

我尝试了下面的代码:

cmd := exec.Command("myapp") // 这个应用程序将内容打印到stderr
stderr, err := cmd.StderrPipe()
if err != nil {
    log.Fatal(err)
}

if err := cmd.Start(); err != nil {
    log.Fatal(err)
}

if b, err := ioutil.ReadAll(stderr); err == nil {
    log.Println(string(b))
}

if err := cmd.Wait(); err != nil {
    log.Fatal(err)
}

这段代码没有输出任何内容。我怀疑这是因为ioutil.ReadAll()不是正确的函数调用,因为它会等待EOF。我应该如何从stderr管道中读取内容?

你可以将执行的命令替换为任何输出到stdout或stderr的命令,比如tail -f mylogfile。关键是,我想要在内容写入stdout时进行处理。

英文:

I have an app called "myapp". That app simply writes to stderr.

The important bit is, I want to capture what is written in stderr and process it in real-time. How would I go about doing that?

I tried the code below. :

cmd := exec.Command("myapp") // this app prints lines to stderr
stderr, err := cmd.StderrPipe()
if err != nil {
    log.Fatal(err)
}

if err := cmd.Start(); err != nil {
    log.Fatal(err)
}

if b, err := ioutil.ReadAll(stderr); err == nil {
    log.Println(string(b))
}                                                                                                       

if err := cmd.Wait(); err != nil {
    log.Fatal(err)
}   

The code doesn't print out anyting. I suspect it's because ioutil.ReadAll() is not the proper func to call since it waits for EOF. How else would I read from the stderr pipe?

You can replace the command executed with anything that outputs to stdout or stderr like tail -f mylogfile. The point is, I want to process the lines as they are written to stdout.

答案1

得分: 4

StderrPipe返回一个ReadCloser。你可以使用它来创建一个bufio.Scanner,然后逐行读取:

sc := bufio.NewScanner(stderr)
for sc.Scan() {
    fmt.Printf("Line: %s\n", sc.Text())
}
英文:

StderrPipe returns a ReadCloser. You can use that to create a bufio.Scanner and then read lines one by one:

sc := bufio.NewScanner(stderr)
for sc.Scan() {
    fmt.Printf("Line: %s\n", sc.Text());
}

答案2

得分: 1

创建一个实现io.Writer接口的类型,并将其设置为command的stderr写入器。

type Processor struct{}

func (Processor) Write(b []byte) (int, error) {
    // 在这里拦截数据
    return os.Stdout.Write(b)
}

func main() {
    cmd := exec.Command("mycommand")
    cmd.Stderr = Processor{}
    _ = cmd.Run()
}
英文:

Create a type that implements io.Writer and set that as the command's stderr writer.

type Processor struct{}

func (Processor) Write(b []byte) (int, error) {
	// intercept data here
	return os.Stdout.Write(b)
}

func main() {
	cmd := exec.Command("mycommand")
	cmd.Stderr = Processor{}
	_ = cmd.Run()
}

huangapple
  • 本文由 发表于 2014年7月9日 01:40:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/24638281.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定