golang exec.Command读取标准输入 [英] golang exec.Command read std input
本文介绍了golang exec.Command读取标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个可以调用ruby脚本的go程序.
I have a go program that should invoke a ruby script.
我有一个 runCommand
函数:
func runCommand(cmdName string, arg ...string) {
cmd := exec.Command(cmdName, arg...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
err = cmd.Run()
if err != nil {
fmt.Printf("Failed to start Ruby. %s\n", err.Error())
os.Exit(1)
}
}
我这样调用它:
runCommand("ruby", "-e", "require 'foo'")
它适用于大多数情况,除非子进程中有一个 gets
或任何类似的操作需要暂停以进行输入.
It works for most cases, except if there is a gets
or any similar operation in the child process that needs to pause for an input.
我尝试设置 cmd.Stdin = os.Stdin
,但是它不等待输入.
I have tried setting cmd.Stdin = os.Stdin
, but it does not wait for input.
我做错了什么?
推荐答案
以下程序似乎可以满足您的要求(我的 runCommand
与您的几乎相同.我只是更改了 =
到:=
的 err
行.)您在做其他事情吗?
The following program seems do what you ask for (my runCommand
is almost identical to yours. I just changed the =
to :=
for the err
line.) Are you doing something differently?
package main
import (
"fmt"
"os"
"os/exec"
)
func main() {
runCommand("ruby", "-e", `puts "Running"; $in = gets; puts "You said #{$in}"`)
}
func runCommand(cmdName string, arg ...string) {
cmd := exec.Command(cmdName, arg...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
err := cmd.Run()
if err != nil {
fmt.Printf("Failed to start Ruby. %s\n", err.Error())
os.Exit(1)
}
}
这篇关于golang exec.Command读取标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文