情况是这样的,我想做一些终端交互,我想启动子线程刷新前N行,用主线程处理用户输入。
之后程序会打印可变字符串,可能还有一些日志。
子线程是这样的:
let mut count: i32 = 0;
loop {
println!("\x1B[2F\x1B[2KHi user1, count:{}\n", count);
count += 1;
let ten_millis = time::Duration::from_millis(1000);
thread::sleep(ten_millis);
}
例如:
----------------
Hi user1, count: 0
Input: 1+1
Output: 2
----------------
刷新代码运行良好,但光标将重置为行首,我想始终将其移动到最后一行的末尾。 我怎样才能做到这一点?
如有任何帮助,我们将不胜感激。
最佳答案
当它归结为四处移动光标时,您可能会对简单的ANSI 转义序列感兴趣:
ANSI escape sequences allow you to move the cursor around the screen at will. This is more useful for full screen user interfaces generated by shell scripts, but can also be used in prompts. The movement escape sequences are as follows:
\033[<L>;<C>H
\033[<L>;<C>f
\033[<N>A
\033[<N>B
\033[<N>C
\033[<N>D
\033[2J
\033[K
\033[s
\033[u
虽然这些 ANSI 转义序列工作得很好,但您可能不时对 tput
的用法感兴趣。因为它为您的脚本提供了更多可读性。讲解 tput
这里会有点矫枉过正,但是上面的命令可以这样完成:
tput cup <L> <C>
tput cuu <N>
tput cud <N>
tput cuf <N>
tput cub <N>
tput clear
tput el
tput sc
tput rc
还有很多很多其他选项可用。见
-
man tput
-
man 5 terminfo
关于bash - 刷新前 N 行并将光标重置到带有转义序列的当前行的末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53773118/