我正在编写一个交互式应用程序,它在循环中接受用户输入并在后台打印响应。我的代码的阅读器部分如下所示:
scanner := bufio.NewReader(os.Stdin)
for {
fmt.Print(":: ") // prompt for user to enter stuff
in,_:=scanner.ReadString('\n')
}
然而,当我在等待用户输入时,我想像这样打印我通过网络获得的一些异步数据:
>> Some text
>> :: Hi I'm the user and I'm
现在一些背景数据到达:
>> Some text
>> This data was printed while user was inputting
>> :: Hi I'm the user and I'm
现在用户可以完成输入了:
>> Some text
>> This data was printed while user was inputting
>> :: Hi I'm the user and I'm entering some text
>> ::
我认为后台例程需要扫描 stdin
的文本,以某种方式删除它,打印它自己的数据,并恢复原始文本。我不知道如何扫描未通过回车键输入的文本,或如何清除一行。我该怎么做?
最佳答案
要清除一行,您可以使用 \r
将光标返回到行首,然后用空格替换该行中的所有字符,然后发出另一个 \r
再次返回行首。例如(如果需要添加更多空格):
fmt.Printf("\r \r")
现在您可以在用户输入的数据之上打印您的背景数据。
那怎么转载用户输入的数据呢?您无法从终端本身读取它,因此您必须在输入时将其保存在某个地方。一种方法是在您的终端上禁用输入缓冲,这样您键入的每个字符都会立即刷新到标准输入,您可以在其中读取它。例如:
var input []byte
reader := bufio.NewReader(os.Stdin)
// disables input buffering
exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()
// append each character that gets typed to input slice
for {
b, err := reader.ReadByte()
if err != nil {
panic(err)
}
input = append(input, b)
}
所以当你需要插入背景数据时,先清空这一行,然后打印你的背景数据,最后在下一行打印输入变量的内容。
关于go - 在 Go 中等待用户输入时如何打印到控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39839661/