Golang执行命令-对话框

时间:2019-01-22 22:33:33

标签: go exec

Go程序运行带有参数的外部soft.exe:

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

fmt.Printf("%s", out)

soft.exe文件具有一些输出并等待输入值,例如:

  

请选择代码:   1,2,3,4

通常,在外壳窗口中,我只键入“ 1”并按Enter,然后soft.exe给出结果。

  

谢谢,您的验证码是[一些数字]

运行后如何填充“ 1”并使用GoLang获得输出?在我的示例中,运行soft.exe后,它立即完成“请选择代码:1、2、3、4”的工作。

1 个答案:

答案 0 :(得分:2)

您需要将os.Stdin重定向到cmd.Stdin,将os.Stdout重定向到cmd.Stdout

参见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

此示例在Windows上进行了测试。

package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("yo")
    cmd.Stderr = os.Stderr
    cmd.Stdout = os.Stdout
    cmd.Stdin = os.Stdin
    if err := cmd.Run(); err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

}