英文:
Go - write to stdin on external command
问题
我有以下代码,它执行一个外部命令并将输出打印到控制台,等待用户输入两个字段。一个用于用户名,另一个用于密码,然后我手动添加它们。
有人可以给我一个提示,如何在程序内部写入stdin以输入这些输入?
对我来说棘手的部分是有两个不同的字段等待输入,我不知道如何依次填充它们。
login := exec.Command(cmd, "login")
login.Stdout = os.Stdout
login.Stdin = os.Stdin
login.Stderr = os.Stderr
err := login.Run()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
解决方案:
login := exec.Command(cmd, "login")
var b bytes.Buffer
b.Write([]byte(username + "\n" + pwd + "\n"))
login.Stdout = os.Stdout
login.Stdin = &b
login.Stderr = os.Stderr
英文:
I have the following code which executes an external command and output to the console two fields waiting for the user input.
One for the username and other for the password, and then I have added them manually.
Could anyone give me a hint about how to write to stdin in order to enter these inputs from inside the program?
The tricky part for me is that there are two different fields waiting for input, and I'm having trouble to figure out how to fill one after the other.
login := exec.Command(cmd, "login")
login.Stdout = os.Stdout
login.Stdin = os.Stdin
login.Stderr = os.Stderr
err := login.Run()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
SOLUTION:
login := exec.Command(cmd, "login")
var b bytes.Buffer
b.Write([]byte(username + "\n" + pwd + "\n"))
login.Stdout = os.Stdout
login.Stdin = &b
login.Stderr = os.Stderr
答案1
得分: 9
我想你可以使用bytes.Buffer
来实现这个功能。类似这样:
login := exec.Command(cmd, "login")
buffer := bytes.Buffer{}
buffer.Write([]byte("username\npassword\n"))
login.Stdin = &buffer
login.Stdout = os.Stdout
login.Stderr = os.Stderr
err := login.Run()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
关键在于stdin
只是一个字符缓冲区,当读取凭据时,它会简单地读取字符,直到遇到\n
字符(或者可能是\n\r
)。因此,你可以预先将它们写入缓冲区,并直接将缓冲区提供给命令。
英文:
I imagine you could use a bytes.Buffer
for that.
Something like that:
login := exec.Command(cmd, "login")
buffer := bytes.Buffer{}
buffer.Write([]byte("username\npassword\n"))
login.Stdin = &buffer
login.Stdout = os.Stdout
login.Stderr = os.Stderr
err := login.Run()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
The trick is that the stdin
is merely a char buffer, and when reading the credentials, it will simply read chars until encountering a \n
character (or maybe \n\r
). So you can write them in a buffer in advance, and feed the buffer directly to the command.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论