英文:
Can not run bash `read` command from Golang
问题
我尝试使用基本的bash命令read
从键盘捕获单个字符,但是即使我尝试了几种方法,似乎很难获得输出。
示例代码:
fmt.Println(exec.Command("read", "-t", "5", "-n", "1").Output())
它的意思是“等待5秒钟从键盘获取1个输入字符”。从上面的代码中,我期望看到我的输入字符与其错误一起打印出来,但实际上我得到的是:
输出:
[] exit status 1
这个输出立即在不到1秒的时间内打印出来,这与read
命令的"-t", "5"
参数表示等待5秒的含义相冲突。我尝试在1秒内输入一些字符,但似乎根本不起作用。
顺便说一下,如果尝试这样做:
fmt.Println(exec.Command("echo", "\"Hi!\"").Output())
输出:
[34 104 105 34 10] <nil>
这里使用简单的echo
命令似乎可以工作。
英文:
I tried to use a basic bash command read
to capture a single character from a keyboard. But it seemed difficult to get the output even I try several ways.
Sample code:
fmt.Println(exec.Command("read", "-t", "5", "-n", "1").Output())
Its meaning is "waiting for 5 seconds to get 1 input character from the keyboard". From code above I expected to see my input character printed out together with its error but what do I get is
Output:
[] exit status 1
This output is just immediately printed in lesser than 1 second which conflicts to "-t", "5"
argument of read
command which stands for waiting for 5 second. I try to type some character within 1 second but it seems doesn't work at all.
BTW, if try this
fmt.Println(exec.Command("echo", "\"Hi!\"").Output())
output:
[34 104 105 34 10] <nil>
It seems work here with simple echo
here.
答案1
得分: 2
你没有向命令提供标准输入(stdin),所以它无法读取任何内容并立即退出。
如果你想将其与调用程序的标准输入(stdin)连接起来,可以使用以下代码:
cmd := exec.Command("read", "-t", "5", "-n", "1")
cmd.Stdin = os.Stdin
out, err := cmd.CombinedOutput()
fmt.Println("error:", err)
fmt.Printf("output: %q\n", out)
然而,这段代码不会输出任何内容,因为/usr/bin/read
脚本不会打印任何内容。你可能希望在shell的上下文中调用内置的read
命令,这样会打印读取的字符:
cmd := exec.Command("bash", "-c", "read -t 5 -n 1 C && echo -n $C")
cmd.Stdin = os.Stdin
但最好的方法是直接在Go中从标准输入(stdin)中读取数据。
英文:
You're not providing the command with stdin, so there's nothing it can read and it exits immediately.
If you want to hook it up the same stdin as the calling program, you can use:
cmd := exec.Command("read", "-t", "5", "-n", "1")
cmd.Stdin = os.Stdin
out, err := cmd.CombinedOutput()
fmt.Println("error:", err)
fmt.Printf("output: %q\n", out)
This however won't output anything, since the /usr/bin/read
script isn't going to print anything. You probably want the shell builtin read
to be called in the context of a shell. This would print the character read:
cmd := exec.Command("bash", "-c", "read -t 5 -n 1 C && echo -n $C")
cmd.Stdin = os.Stdin
But in the end, you should probably just read directly from stdin in go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论