目前有一个程序需要启用另外一个code.exe程序来做转码处理
此程序运行后是一个死循环的,就等待输入按回车后就返回相应的解码数据
现在用exec.Command启动程序后就只能使用管道输入一次,代码如下
```
cmd := exec.Command("./code.exe")
var pipIn,pipOut bytes.Buffer
cmd.Stdin = &pipIn
cmd.Stdout = &pipOut
cmd.Run()
pipIn.WriteString(fmt.Sprintf("%s\n", "35063812556aa2cdd6d1cbd"))
time.Sleep(time.Millisecond * 500)
fmt.Println(strings.Replace(pipOut.String(), "\n", "", 1))
pipIn.WriteString(fmt.Sprintf("%s\n", "350632125e6aa2cdded1c"))
time.Sleep(time.Millisecond * 500)
fmt.Println(strings.Replace(pipOut.String(), "\n", "", 1))
```
并不能得到第二次输入的数据解码后的结果
可有其它方法实现长时运行code.exe程序,可以循环输入并得到输出结果的方法?
类似于python的spawn
新手对标准库还不熟悉,还请各大神指教!
解决方案如下:
```
1 DecodeCmd = exec.Command("code.exe")
2 pipIn, _ := rabbit.DecodeCmd.StdinPipe()
3 pipOut, _ := rabbit.DecodeCmd.StdoutPipe()
4 DecodeCmd.Start()
5 CmdBufReader = bufio.NewReader(pipOut)
6 CmdBufWriter = bufio.NewWriter(pipIn)
7
8 CmdBufWriter.WriteString(fmt.Sprintf("%s\n", "35063812556aa2cdd6d1cbd"))
9 CmdBufWriter.Flush()
10 code, _, _ := r.CmdBufReader.ReadLine()
11 CmdBufWriter.WriteString(fmt.Sprintf("%s\n", "350632125e6aa2cdded1c"))
12 CmdBufWriter.Flush()
13 code, _, _ = r.CmdBufReader.ReadLine()
```
#4
更多评论
供参考:
```
package main
import (
"bufio"
"fmt"
"io"
"os/exec"
)
func encode(r *bufio.Reader, w io.Writer, str string) string {
w.Write([]byte(str))
w.Write([]byte("\n"))
str, err := r.ReadString('\n')
if err != nil {
panic(err)
}
// skip '\n'
return str[:len(str)-1]
}
func main() {
cmd := exec.Command(`./code.exe`)
inr, inw := io.Pipe()
outr, outw := io.Pipe()
cmd.Stdin = inr
cmd.Stdout = outw
if err := cmd.Start(); err != nil {
panic(err)
}
go cmd.Wait()
strs := []string{
"35063812556aa2cdd6d1cbd",
"350632125e6aa2cdded1c",
}
for _, str := range strs {
result := encode(bufio.NewReader(outr), inw, str)
fmt.Println(result)
}
}
```
#2