英文:
GO lang : Communicate with shell process
问题
你可以使用io.WriteString
函数将输入写入到in
中,然后通过in.Close()
关闭输入流。这样,你就可以执行shell脚本并读取结果了。以下是一个示例代码:
package main
import (
"fmt"
"io"
"os/exec"
)
func main() {
cmd := exec.Command("python", "add.py")
in, _ := cmd.StdinPipe()
go func() {
defer in.Close()
io.WriteString(in, "your_input_here")
}()
out, _ := cmd.Output()
fmt.Println(string(out))
}
在上面的代码中,我们使用io.WriteString
将输入写入到in
中,并通过in.Close()
关闭输入流。然后,我们使用cmd.Output()
获取脚本的输出结果,并将其打印出来。你可以将"your_input_here"替换为你想要提供给脚本的输入。
英文:
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
?
答案1
得分: 7
以下是一段写入进程并从中读取的代码:
package main
import (
"bufio"
"fmt"
"os/exec"
)
func main() {
// 要计算的内容
calcs := make([]string, 2)
calcs[0] = "3*3"
calcs[1] = "6+6"
// 存储结果
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()
// 逐行读取
bufOut := bufio.NewReader(out)
// 启动进程
if err = cmd.Start(); err != nil {
panic(err)
}
// 将操作写入进程
for _, calc := range calcs {
_, err := in.Write([]byte(calc + "\n"))
if err != nil {
panic(err)
}
}
// 从进程中读取结果
for i := 0; i < len(results); i++ {
result, _, err := bufOut.ReadLine()
if err != nil {
panic(err)
}
results[i] = string(result)
}
// 查看计算结果
for _, result := range results {
fmt.Println(result)
}
}
你可能希望在不同的 goroutine 中进行读写操作。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论