Process GO lang:与shell进程通信
我想从Go执行一个shell脚本。 shell脚本接受标准输入并回显结果 我想从GO提供这个输入,并使用结果 我正在做的是:Process GO lang:与shell进程通信,process,go,ipc,stdout,stdin,Process,Go,Ipc,Stdout,Stdin,我想从Go执行一个shell脚本。 shell脚本接受标准输入并回显结果 我想从GO提供这个输入,并使用结果 我正在做的是: cmd := exec.Command("python","add.py") in, _ := cmd.StdinPipe() 但是如何从中的读取呢?下面是一些向进程写入代码并从中读取的代码: package main import ( "bufio" "fmt" "os/exec" ) func main() { //
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)
}
}
主程序包
进口(
“布菲奥”
“fmt”
“os/exec”
)
func main(){
//我们要计算的是什么
计算:=make([]字符串,2)
计算[0]=“3*3”
计算[1]=“6+6”
//存储结果
结果:=make([]字符串,2)
cmd:=exec.Command(“/usr/bin/bc”)
在中,err:=cmd.StdinPipe()
如果错误!=零{
恐慌(错误)
}
延迟进入。关闭()
out,err:=cmd.StdoutPipe()
如果错误!=零{
恐慌(错误)
}
推迟结束
//我们想逐行阅读
bufOut:=bufio.NewReader(out)
//开始这个过程
如果err=cmd.Start();err!=nil{
恐慌(错误)
}
//将操作写入进程
对于u,计算:=范围计算{
_,err:=in.Write([]字节(计算+“\n”))
如果错误!=零{
恐慌(错误)
}
}
//从过程中读取结果
对于i:=0;i
您可能希望在不同的goroutine中读取/写入进程 你不能从里面读,那是个作家。你试过给它写信吗?