加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

GO lang:与shell进程通信

发布时间:2020-12-15 21:17:46 所属栏目:安全 来源:网络整理
导读:我想从Go执行一个 shell脚本. shell脚本采用标准输入并回显结果. 我想从GO提供此输入并使用结果. 我在做的是: cmd := exec.Command("python","add.py") in,_ := cmd.StdinPipe() 但我怎么读? 解决方法 以下是一些代码写入进程并从中读取: package mainimp
我想从Go执行一个 shell脚本.
shell脚本采用标准输入并回显结果.

我想从GO提供此输入并使用结果.

我在做的是:

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

但我怎么读?

解决方法

以下是一些代码写入进程并从中读取:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读