Nick M
Nick M

Reputation: 23

Golang exec.Command - Dialog

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".

Upvotes: 0

Views: 1587

Answers (1)

Billy Yuan
Billy Yuan

Reputation: 1295

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)
    }

}

Upvotes: 4

Related Questions