0

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
  • Could you clarify your question @Yaros? Its not clear what you're trying to accomplish? Also, including your code is always a good idea. Commented Jan 22, 2019 at 22:36

1 Answer 1

4

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

}
Sign up to request clarification or add additional context in comments.

1 Comment

yo is a npm tool, asks for your choice, and then generates project for you. Just like you described: choose code, then print code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.