【问题标题】:Pipe string into STDIN of command in Golang在 Golang 中将字符串输入到命令的 STDIN
【发布时间】:2018-09-28 18:31:27
【问题描述】:

我想在 Golang 中复制以下 subprocess.run 函数调用。正确的方法是什么?

subprocess.run(['kinit', username], input=password.encode())

到目前为止,我已经弄清楚如何使用exec.Command 来运行外部命令,但让我感到困惑的是将字符串作为输入传递给该命令的STDIN。 Python 的subprocess.run 有一个方便的input 参数来处理这个问题,我怎样才能在Golang 中获得类似的结果?

【问题讨论】:

    标签: go subprocess pipe exec piping


    【解决方案1】:

    我想出了办法。

    package main
    
    import "os/exec"
    import "strings"
    
    func main() {
        cmd := exec.Command("kinit", username)
        cmd.Stdin = strings.NewReader(password)
        err := cmd.Run()
    }
    

    Command 对象的Stdin 属性是STDIN 管道,我们可以将其设置为包含输入字符串的strings.NewReader 对象,以达到与问题中提到的Python 截图相同的效果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      相关资源
      最近更新 更多