2019-01-22 22:33
浏览 119


Go program run external soft.exe with arguments:

cmd := exec.Command("soft.exe", "-text")
out, _ := cmd.CombinedOutput()

fmt.Printf("%s", out)

soft.exe file has some output and wait for input value, for example:

Please choose code: 1, 2, 3, 4

In usual way in shell window I just type "1" and press Enter, and soft.exe give me result.

Thank you, your code is [some number]

How can I fill "1" after run and get output with GoLang? In my example after run soft.exe it immediately finish working with "Please choose code: 1, 2, 3, 4".

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douchang6770
    douchang6770 2019-01-23 04:52

    You need to redirect os.Stdin to cmd.Stdin, os.Stdout to cmd.Stdout

    See in godoc: https://golang.org/pkg/os/exec/#Cmd

       // Stdin specifies the process's standard input.
       // If Stdin is nil, the process reads from the null device (os.DevNull).
       // If Stdin is an *os.File, the process's standard input is connected
       // directly to that file.
       // Otherwise, during the execution of the command a separate
       // goroutine reads from Stdin and delivers that data to the command
       // over a pipe. In this case, Wait does not complete until the goroutine
       // stops copying, either because it has reached the end of Stdin
       // (EOF or a read error) or because writing to the pipe returned an error.
       Stdin io.Reader

    This sample was tested on windows.

    package main
    import (
    func main() {
        cmd := exec.Command("yo")
        cmd.Stderr = os.Stderr
        cmd.Stdout = os.Stdout
        cmd.Stdin = os.Stdin
        if err := cmd.Run(); err != nil {
    点赞 评论