如何从标准输出中返回值?

问题描述 投票:-1回答:1

我正在用其他语言编写REPL / shell。

我有以下代码,我希望打印2,但是什么都没打印。

grepCmd := exec.Command("python")
grepIn, _ := grepCmd.StdinPipe()
grepOut, _ := grepCmd.StdoutPipe()
grepCmd.Start()
grepIn.Write([]byte("1+1"))  <- assume this is fixed and we cannot use print().
//grepIn.Write([]byte("print(1+1)")) This one returns 2
grepIn.Close()
grepBytes, _ := ioutil.ReadAll(grepOut)
grepCmd.Wait()
fmt.Println(string(grepBytes)

我不问如何使用cmd.stdout = os.stdout

go read-eval-print-loop
1个回答
0
投票

当stdin连接到管道时,默认情况下python解释器将以非交互模式运行。因此,如果您在shell中运行echo "1+1" | python,您将不会从stdout获得任何帮助。

执行python -i以显式启用交互模式,如echo "1+1" | python -i中一样。

© www.soinside.com 2019 - 2024. All rights reserved.