How to run .exe program using Golang? The program should start in the new main.exe window (The program has an I / O stream, reading data from the keyboard)

 package main import ( "fmt" "os/exec" "time" ) func main() { output, err := exec.Command("main.exe").Output() if err != nil { fmt.Println(err.Error()) } fmt.Println(string(output)) time.Sleep(time.Second * 3) } 

I start, nothing appears, main.exe appears in the task main.exe , but it is inactive, because as I said above, it reads the data and then acts. If I rewrite main.exe without reading the data from the keyboard, then the program will start and everything will be fine displayed on the screen. How to make so that programs which read data from the keyboard were normally carried out / worked?

  • "new window" is the cmd.exe window? - ei-grad

2 answers 2

Usually the program inherits the standard input from the one that launched it, that is, the input must be made in the current window. But in Golang exec.Cmd, by default, input is overridden to a null device :

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

You can override it back:

 cmd := exec.Command("main.exe") cmd.Stdin = os.Stdin 

If you need a separate window - you can run a separate cmd.exe:

 exec.Command("cmd.exe", "/C", "main.exe") 
  • I do not know why, maybe I did something wrong, but this method did not work. But when I added the start argument, my program started up perfectly in a new window :) - Mothership

As I understood, to launch in a new window, you just need to add the start argument:

 cmd := exec.Command("cmd", "/C", "start", "main.exe") cmd.Start()