英文:
What is the propper way to break hanging scaner?
问题
这是来自Go文档的一个示例,它只是等待标准输入(STDIN)的输入而挂起:
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
如果读取一个空文件,也会发生同样的情况。
如何正确中断挂起的扫描器?
唯一想到的解决方案是定期检查扫描器是否接收到新数据。
有一种感觉,我可能忽略了一些无聊的东西,解决方案实际上可能非常简单和明显。
英文:
This is an example from Go docs, that just hangs waiting for STDIN input:
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
The same thing happens if you read an empty file.
What is the propper way to break hanging scanner?
The only solution that comes to mind is a periodic check to see if scanner has received new data.
There is a feeling that I'm missing some nonsense and the solution is actually obscenely simple and obvious.
答案1
得分: 1
你无法终止Scanner.Scan()
的调用。你需要循环执行,直到Scanner.Scan()
返回true
为止。只要成功读取到行(无论是否为空),Scanner.Scan()
就会持续返回true
。只有当到达输入的末尾或者读取失败时,它才会返回false
。
所以,要退出循环,你需要在终端上发送“输入结束”的信号。在Unix系统上,可以通过按下<kbd>CTRL</kbd>+<kbd>D</kbd>来实现;在Windows上,可以通过按下<kbd>CTRL</kbd>+<kbd>Z</kbd>来实现。
当然,你也可以修改循环体,添加一个条件(if
语句),以便在输入特定内容(例如exit
)时终止循环:
for scanner.Scan() {
line := scanner.Text()
fmt.Println(line)
if line == "exit" {
break
}
}
英文:
You can't end (terminate) a Scanner.Scan()
call.
You loop until Scanner.Scan()
keeps returns true
. Scanner.Scan()
will keep returning true
as long as lines (be them empty or not) are successfully read. It returns false
if end of input is reached or reading fails.
So for you to exit the loop, you have to "transmit" end of input signal on your terminal. This can be done by pressing <kbd>CTRL</kbd>+<kbd>D</kbd> on unix systems, and <kbd>CTRL</kbd>+<kbd>Z</kbd> on Windows.
Of course you can modify the loop body, and add a condition (if
) to terminate if a certain input is entered, e.g. exit
:
for scanner.Scan() {
line := scanner.Text()
fmt.Println(line)
if line == "exit" {
break
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论