H
H
hitakiri2017-02-15 12:03:12
go
hitakiri, 2017-02-15 12:03:12

How to call and work with exe file using golang in windows?

There is an exe-shnik ( for.exe ) lying in the same folder with the go script. for.exe calls a cmd window to enter a few options, and can also be accessed from the command line. The task is to call for.exe using a go script and enter the necessary parameters.

cmd := exec.Command("cmd", "/C", "C:/gopath/src/script/for.exe")
  err := cmd.Start()
  if err != nil {
    log.Fatal(err)
  }
  var out bytes.Buffer
  cmd.Stdout = &out
  fmt.Printf("Вывод in caps: %q\n", out.String())
  fmt.Printf("Вывод: %v\n", out.String())

It gives an empty string, although when running for.exe it sends "Start" to the command line
Enter parameters
cmd.Stdin = strings.NewReader("param1")
It also fails.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Tomilov, 2017-02-15
@hitakiri

In addition to Alexander's answer, if you need to not only read some data from a third-party program, but also enter something into its standard input stream (as I understand it, this is the main task), you can do this:

package main

import (
  "fmt"
  "log"
  "os/exec"
)

func main() {
  cmd := exec.Command("cmd", "/C", "C:/gopath/src/script/for.exe")

  // Чтобы вводить что-то в стандартный поток ввода другой программы, нужно получить ее pipe.
  pipe, err := cmd.StdinPipe()
  if err != nil {
    log.Fatal(err)
  }
  // Куда впоследствии можно что-то писать.
  pipe.Write([]byte("piggybank"))
  // После ввода всех данных нужно обязательно его закрыть.
  pipe.Close()

  // Самый простой способ получить вывод другой программы, использовать:
  output, err := cmd.Output()
  if err != nil {
    log.Fatal(err)
  }
  fmt.Print(string(output))
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question