你可以使用Go的os/exec库将错误消息传递到你的Go程序中。

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

How can I get the error message into my Go program using Go's os/exec library?

问题

我正在运行执行"psql"的代码。它应该返回一些错误代码,因为数据库没有启动。

它应该返回以下内容:

psql: could not connect to server: No such file or directory 	Is the server running locally and accepting 	connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

然而,它返回的是标准错误信息:

2013/11/21 15:06:19 exit status 2
exit status 1

以下是代码:

package main

import (
        "fmt"
        "log"
        "os/exec"

)

func main() {
        out, err := exec.Command("psql").Output()
        if err != nil {
                log.Fatal(err)
        }
        fmt.Printf("%s\n",out)
}
英文:

I am running code that executes "psql". It should return some error code, because the database is not up.

It should return

psql: could not connect to server: No such file or directory 	Is the server running locally and accepting 	connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

However it returning the standard error of

2013/11/21 15:06:19 exit status 2
exit status 1

Here is the code

package main

import (
        "fmt"
        "log"
        "os/exec"

)

func main() {
        out, err := exec.Command("psql").Output()
        if err != nil {
                log.Fatal(err)
        }
        fmt.Printf("%s\n",out)
}

答案1

得分: 2

因为输出只返回来自STDOUT的数据,而psql错误是在STDERR流上打印该数据。

您需要读取STDERR:

func (c *Cmd) StderrPipe() (io.ReadCloser, error)
英文:

Because output only returns data from the STDOUT, while the psql error is printing that data on the STDERR stream

You need to read the STDERR:

func (c *Cmd) StderrPipe() (io.ReadCloser, error)

huangapple
  • 本文由 发表于 2013年11月22日 04:07:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/20130877.html
匿名

发表评论

匿名网友

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

确定