首页 > 解决方案 > 如何从标准输出返回值?

问题描述

我正在为其他语言构建一个 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.

标签: goread-eval-print-loop

解决方案


当标准输入连接到管道时,python 解释器默认以非交互模式运行。因此,如果您echo "1+1" | python在 shell 中运行,您将不会从 stdout 获得任何信息。

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


推荐阅读