3 回答

TA貢獻1809條經驗 獲得超8個贊
該程序正在阻塞,因為子fmt.Scanln進程中的 正在等待該\n字符(anEOF也會導致它返回)。為了避免阻塞,您的輸入應該包含兩個\ns,或者您可以只調用“stdin.Close()”來指示輸入流已完成。
并且由于子流程多次調用Scanln和Println,因此單次調用stdout.Read可能無法讀取子流程的完整輸出。您可以繼續調用stdout.Read()直到io.EOF返回錯誤,或者只使用ioutil.ReadAll.
func main() {
cmd := exec.Command("G:\\go_workspace\\GOPATH\\src\\pjx\\modules\\exec\\exec")
stdin, e := cmd.StdinPipe()
if e != nil {
panic(e)
}
stdout, e := cmd.StdoutPipe()
if e != nil {
panic(e)
}
if e := cmd.Start(); e != nil {
panic(e)
}
_, e = stdin.Write([]byte("hello\nworld\n"))
if e != nil {
panic(e)
}
stdin.Close()
out, _ := ioutil.ReadAll(stdout)
// or you can use a loop
//for {
// var buf = make([]byte, 512)
// n, e := stdout.Read(buf)
// if e == io.EOF {
// break
// }
// if e != nil {
// panic(e)
// }
// fmt.Println(string(buf[:n]))
//}
fmt.Println(string(out))
if e := cmd.Wait(); e != nil {
panic(e)
}
}

TA貢獻1850條經驗 獲得超11個贊
一種方法可以做到這一點
cmd := exec.Command("...") // Change to your path
stdin, err := cmd.StdinPipe()
if err != nil {
panic(err)
}
stdout, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
buf := bytes.NewBuffer(nil)
// read the stdout continuously in a separate goroutine and capture it in buf
go func() {
io.Copy(buf, stdout)
}()
if err := cmd.Start(); err != nil {
panic(err)
}
stdin.Write([]byte("hello\n")) // Send \n to submit
stdin.Write([]byte("world\n"))
if err := cmd.Wait(); err != nil {
panic(err)
}
fmt.Fprint(os.Stdout, buf)
結果:
? go run main.go
input a value
hello
input another value
world

TA貢獻1757條經驗 獲得超8個贊
您需要監聽正在執行的程序的輸出。當您寫“hello”時,程序可能仍在寫入其標準輸出。嘗試這個:
go func() {
in := bufio.NewReader(stdout)
for {
s, err := in.ReadString('\n')
if err != nil {
return
}
fmt.Println(s)
}
}()
if e := cmd.Start(); e != nil {
panic(e)
}
stdin.Write([]byte("hello\n"))
stdin.Write([]byte("hello2\n"))
if e := cmd.Wait(); e != nil {
panic(e)
}
- 3 回答
- 0 關注
- 216 瀏覽
添加回答
舉報