简体   繁体   中英

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

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)
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM