dsjojts9734 2019-01-22 22:33
浏览 209
已采纳

Golang执行命令-对话框

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 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 (
        "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)
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里