dqydp44800 2015-05-13 06:16
浏览 732
已采纳

golang exec.Command读取标准输入

I have a go program that should invoke a ruby script.

I have a runCommand function:

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
", err.Error())
        os.Exit(1)
    }
}

I invoke it like this:

runCommand("ruby", "-e", "require 'foo'")

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.

I have tried setting cmd.Stdin = os.Stdin, but it does not wait for input.

What am I doing wrong?

  • 写回答

2条回答 默认 最新

  • dps69208 2015-05-14 13:03
    关注

    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
    ", err.Error())
            os.Exit(1)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作