how can I get stdin to exec cmd in golang

后端 未结 4 1063
故里飘歌
故里飘歌 2021-02-07 06:32

I have this code

subProcess := exec.Cmd{
    Path: execAble,
    Args: []string{
        fmt.Sprintf(\"-config=%s\", *configPath),
        fmt.Sprintf(\"-serverT         


        
4条回答
  •  萌比男神i
    2021-02-07 07:02

    There's now an updated example available in the Go docs: https://golang.org/pkg/os/exec/#Cmd.StdinPipe

    If the subprocess doesn't continue before the stdin is closed, the io.WriteString() call needs to be wrapped inside an anonymous function:

    func main() {
        cmd := exec.Command("cat")
        stdin, err := cmd.StdinPipe()
        if err != nil {
            log.Fatal(err)
        }
    
        go func() {
            defer stdin.Close()
            io.WriteString(stdin, "values written to stdin are passed to cmd's standard input")
        }()
    
        out, err := cmd.CombinedOutput()
        if err != nil {
            log.Fatal(err)
        }
    
        fmt.Printf("%s\n", out)
    }
    

提交回复
热议问题