GO语言:与Shell进程通信

4

我希望可以从Go中执行一个Shell脚本。

这个Shell脚本需要标准输入并输出结果。

我希望能够从GO中提供输入并使用它的结果。

我的做法如下:

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

但是我该如何从 in 中读取数据呢?

你不能从中读取,它是一个 Writer。你尝试过向其中写入吗? - JimB
1个回答

7

以下是编写进程并从中读取的代码:

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

您可能想在不同的goroutine中读取/写入进程。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接