英文:
end input programmatically in a golang terminal application
问题
我正在尝试在3秒内以编程方式结束终端输入并输出结果。
我的代码如下:
package main
import (
"bufio"
"fmt"
"os"
"time"
)
var (
result string
err error
)
func main() {
fmt.Println("请输入一些内容,你有3000毫秒的时间")
go func() {
time.Sleep(time.Millisecond * 3000)
fmt.Println("到了结束输入的时间,读取你已经输入的内容")
fmt.Println("result")
fmt.Println(result)
}()
in := bufio.NewReader(os.Stdin)
result, err = in.ReadString('\n')
if err != nil {
fmt.Println(err)
}
}
输出结果:
请输入一些内容,你有3000毫秒的时间
hello 到了结束输入的时间,读取你已经输入的内容
result
我只打印了hello
,然后经过了3秒,程序应该结束输入并读取我的hello
并输出:
result
hello
但是我不知道如何实现这一点。是否可能在没有用户意图的情况下结束终端输入并读取输入的值?
英文:
I am trying to end terminal input programmatically in 3 seconds and output the result.
My code is the following:
package main
import (
"bufio"
"fmt"
"os"
"time"
)
var (
result string
err error
)
func main() {
fmt.Println("Please input something, you have 3000 milliseconds")
go func() {
time.Sleep(time.Millisecond * 3000)
fmt.Println("It's time to break input and read what you have already typed")
fmt.Println("result")
fmt.Println(result)
}()
in := bufio.NewReader(os.Stdin)
result, err = in.ReadString('\n')
if err != nil {
fmt.Println(err)
}
}
The output:
Please input something, you have 3000 milliseconds
hello It's time to break input and read what you have already typed
result
I just printed hello
and 3 seconds passed and the program should end the input and read my hello
and give output:
result
hello
But I don't know how to provide this. Is it possible to end terminal input without user's intention and read the inputted value?
答案1
得分: 2
你无法直接对标准输入流(stdin)设置超时,所以你需要在接收读取协程结果的过程中创建一个超时机制:
func getInput(input chan string) {
in := bufio.NewReader(os.Stdin)
result, err := in.ReadString('\n')
if err != nil {
log.Fatal(err)
}
input <- result
}
func main() {
input := make(chan string, 1)
go getInput(input)
select {
case i := <-input:
fmt.Println(i)
case <-time.After(3000 * time.Millisecond):
fmt.Println("超时")
}
}
这段代码会创建一个名为input
的字符串通道,并在一个单独的协程中调用getInput
函数来读取标准输入。然后,通过select
语句来等待输入结果或超时信号。如果在3秒内成功接收到输入结果,就会打印出来;否则,会打印"超时"。
英文:
You can't timeout the read on stdin directly, so you need to create a timeout around receiving the result from the reading goroutine:
func getInput(input chan string) {
in := bufio.NewReader(os.Stdin)
result, err := in.ReadString('\n')
if err != nil {
log.Fatal(err)
}
input <- result
}
func main() {
input := make(chan string, 1)
go getInput(input)
select {
case i := <-input:
fmt.Println(i)
case <-time.After(3000 * time.Millisecond):
fmt.Println("timed out")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论