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

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

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

问题

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

它应该返回以下内容:

  1. 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"?

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

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

以下是代码:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os/exec"
  6. )
  7. func main() {
  8. out, err := exec.Command("psql").Output()
  9. if err != nil {
  10. log.Fatal(err)
  11. }
  12. fmt.Printf("%s\n",out)
  13. }
英文:

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

It should return

  1. 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

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

Here is the code

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os/exec"
  6. )
  7. func main() {
  8. out, err := exec.Command("psql").Output()
  9. if err != nil {
  10. log.Fatal(err)
  11. }
  12. fmt.Printf("%s\n",out)
  13. }

答案1

得分: 2

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

您需要读取STDERR:

  1. 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:

  1. 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:

确定