这是你的代码的工作版本(python代码没有变化).
注意:检查所有错误,修复-u标志,使用bufio读取一行,并使用Wait等待进程结束.
import (
"bufio"
"fmt"
"log"
"os/exec"
)
func main() {
c := exec.Command("python", "-u", "add.py")
si, err := c.StdinPipe()
if err != nil {
log.Fatal(err)
}
so, err := c.StdoutPipe()
if err != nil {
log.Fatal(err)
}
reader := bufio.NewReader(so)
err = c.Start()
if err != nil {
log.Fatal(err)
}
// Now do some maths
for i := 0; i < 10; i++ {
sum := fmt.Sprintf("2+%d\n", i)
_, err = si.Write([]byte(sum))
if err != nil {
log.Fatal(err)
}
answer, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
fmt.Printf("Answer to %q is %q\n", sum, answer)
}
// Close the input and wait for exit
si.Close()
so.Close()
c.Wait()
}
哪个产生
Answer to "2+0\n" is "2\n"
Answer to "2+1\n" is "3\n"
Answer to "2+2\n" is "4\n"
Answer to "2+3\n" is "5\n"
Answer to "2+4\n" is "6\n"
Answer to "2+5\n" is "7\n"
Answer to "2+6\n" is "8\n"
Answer to "2+7\n" is "9\n"
Answer to "2+8\n" is "10\n"
Answer to "2+9\n" is "11\n"