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 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题