dtc66318
2019-09-04 02:33
浏览 137
已采纳

如何在Golang中使用os / exec处理用户输入? 我无法停止输入阶段

First, I build a command as exec.exe from this:

package main
import "fmt"
func main() {
    var input string
    fmt.Println("input a value")
    fmt.Scanln(&input)
    fmt.Println(input)

    fmt.Println("input another value")
    fmt.Scanln(&input)
    fmt.Println(input)
}

Then I want to use os/exec pacage to run it:

package main

import (
    "fmt"
    "os/exec"
)

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)
    }
    stdin.Write([]byte("hello"))
    var buf = make([]byte, 512)
    n, e := stdout.Read(buf)
    if e != nil {
        panic(e)
    }
    fmt.Println(string(buf[:n]))

    if e := cmd.Wait(); e != nil {
        panic(e)
    }
}

Finally I run it, and result will pause on the user input stage,like:

(in case picture is not loaded, they're paused on input stage)

please input a value:

1
12
232

unexpected result, pausing on user input stage

Did I use cmd pipe in a wrong way?

3条回答 默认 最新

相关推荐 更多相似问题