Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GO lang : Communicate with shell process

I want to execute a shell script from Go. The shell script takes standard input and echoes the result.

I want to supply this input from GO and use the result.

What I am doing is:

  cmd := exec.Command("python","add.py")  
  in, _ := cmd.StdinPipe()

But how do I read from in?

like image 545
Palash Kumar Avatar asked Mar 20 '23 07:03

Palash Kumar


1 Answers

Here is some code writing to a process, and reading from it:

package main

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

func main() {
    // What we want to calculate
    calcs := make([]string, 2)
    calcs[0] = "3*3"
    calcs[1] = "6+6"

    // To store the results
    results := make([]string, 2)

    cmd := exec.Command("/usr/bin/bc")

    in, err := cmd.StdinPipe()
    if err != nil {
        panic(err)
    }

    defer in.Close()

    out, err := cmd.StdoutPipe()
    if err != nil {
        panic(err)
    }

    defer out.Close()

    // We want to read line by line
    bufOut := bufio.NewReader(out)

    // Start the process
    if err = cmd.Start(); err != nil {
        panic(err)
    }

    // Write the operations to the process
    for _, calc := range calcs {
        _, err := in.Write([]byte(calc + "\n"))
        if err != nil {
            panic(err)
        }
    }

    // Read the results from the process
    for i := 0; i < len(results); i++ {
        result, _, err := bufOut.ReadLine()
        if err != nil {
            panic(err)
        }
        results[i] = string(result)
    }

    // See what was calculated
    for _, result := range results {
        fmt.Println(result)
    }
}

You might want to read/write from/to the process in different goroutines.

like image 124
Florent Bayle Avatar answered Mar 28 '23 00:03

Florent Bayle