英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论