1 回答

TA貢獻1833條經(jīng)驗 獲得超4個贊
我發(fā)現(xiàn)通過實驗,我收到了錯誤,因為我正在打電話
stdo,g := ioutil.ReadAll(stdout)
stde,f := ioutil.ReadAll(stderr)
后
d := cmd.Wait()
所以會發(fā)生什么是標(biāo)準(zhǔn)輸出,標(biāo)準(zhǔn)錯誤管道在cmd.Wait()返回后關(guān)閉。
下面是代碼注釋 cmd.StderrPipe()
// StderrPipe returns a pipe that will be connected to the command's
// standard error when the command starts.
// The pipe will be closed automatically after Wait sees the command exit.
所以很明顯,我們無法在 stdout 和 stderr 關(guān)閉后讀取它們。
我們也無法在命令開始之前讀取它們。所以我們必須把它們放在開始和等待之間。
這是修復(fù)該問題的代碼。
package main
import (
"fmt"
"os/exec"
"io/ioutil"
)
func main() {
cmd := exec.Command("psql")
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Printf("Error: %s", err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
fmt.Printf("Error: %s", err)
}
err = cmd.Start()
if err != nil {
fmt.Printf("Start error %s",err)
}
stdo,g := ioutil.ReadAll(stdout)
stde,f := ioutil.ReadAll(stderr)
d := cmd.Wait()
if d != nil {
fmt.Println(d)
}
if g != nil {
fmt.Println(g)
}
if f !=nil {
fmt.Println(f)
}
fmt.Printf("Standard err is %s \n", stde)
fmt.Printf("Standard out is %s \n",stdo)
}
- 1 回答
- 0 關(guān)注
- 275 瀏覽
添加回答
舉報