go - 如何从标准输出返回值?
问题描述
我正在为其他语言构建一个 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
.
解决方案
当标准输入连接到管道时,python 解释器默认以非交互模式运行。因此,如果您echo "1+1" | python
在 shell 中运行,您将不会从 stdout 获得任何信息。
执行python -i
以显式启用交互模式,如echo "1+1" | python -i
.
推荐阅读
- ruby - Ruby 强参数:Integer 的 NoMethodError 未定义方法允许
- python-3.x - 使用 BeautifulSoup 进行网页抓取
- android - Xamarin.Forms Android 应用程序上未显示启动屏幕,其中 VPN 和工作配置文件上的托管设备
- django - 如何在 Django Url 中添加可选的 slug
- excel - 需要从 SSIS 包中为 excel 中的标题着色
- angular - 如何限制 NgSelect 下拉面板中显示的项目数量?
- oracle11g - 出现此错误状态:失败 - 测试失败:IO 错误:网络适配器无法建立连接
- azure - Azure Kubernetes - Istio 从外部访问 grafana、prometheus、jaeger、kiali 和 envoy?
- arrays - 在 Ruby on Rails 应用程序中,我试图在数组中的哈希中循环遍历数组。为什么我会收到“语法错误”消息?
- python - 狮身人面像没有找到任何来源