【问题标题】:GO lang : Communicate with shell processGO lang : 与shell进程通信
【发布时间】:2014-04-10 06:15:47
【问题描述】:

我想从 Go 执行一个 shell 脚本。 shell 脚本采用标准输入并回显结果。

我想从 GO 提供这个输入并使用结果。

我正在做的是:

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

但是我如何阅读in

【问题讨论】:

  • 您无法从 in 中读取,它是 Writer。你试过给它写信吗?

标签: process go ipc stdout stdin


【解决方案1】:

这是一些写入进程并从中读取的代码:

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 中读取/写入进程。

【讨论】:

    猜你喜欢
    • 2014-05-05
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    相关资源
    最近更新 更多