在Golang中将管道串转换为命令的STDIN(Pipe string into STDIN of command in Golang)

编程入门 行业动态 更新时间:2024-10-17 21:29:25
在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中实现类似的结果?

I want to replicate the following subprocess.run function call in Golang. What would be the correct way to do it?

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

So far, I've figured out how to use exec.Command to run external commands, but what's confusing me is passing strings as input to STDIN of that command. Python's subprocess.run has a handy input parameter that takes care of this, how can I achieve similar results in 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剪切相同的效果。

I figured out how to do it.

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

The Stdin attribute of the Command object is the STDIN pipe, we can set it to a strings.NewReader object containing the input string to achieve the same effect as of the Python snipped mentioned in the question.

更多推荐

本文发布于:2023-04-28 04:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329746.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   管道   命令   Golang

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!