在 Golang 中将字符串通过管道传输到命令的 STDIN

Pipe string into STDIN of command in Golang

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

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

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

我知道怎么做了。

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 片段。