如何重置控制台输出?清空只是将输出向后移动。

5
我的控制台应用程序需要清空屏幕。我该如何真正地清空屏幕,就像Linux中的reset命令一样?
我尝试使用在谷歌上找到的方法,例如:
print!("{}[2J", 27 as char); // First attempt
print!("{}", termion::clear::All); // 'termion' crate, version 1.5.3

他们只是往下滚动,把前面的输出留在身后。我想通过Rust执行重置命令,但一定还有其他方法,对吧?


6
请不要这样做。如果一个程序敢于清空我的终端,我会非常生气。你考虑过使用备用屏幕缓冲区吗? - mcarton
1
@mcarton 哦,那很好。我会试试看的。 - Krey Lazory
第一条评论是最佳答案。 - alexzander
1个回答

2

由于没有人回答,我来回答一下。

@mcarton所提到的,您需要使用一个备用屏幕,它将在超出范围后自动重置所有内容。

基本上,这将在当前的终端屏幕上创建一个虚拟屏幕,该屏幕将定位于旧屏幕的相同坐标,具有相同的高度和宽度。简而言之,就像是复制

在程序中,您将在备用屏幕上写入和删除,而不会损坏您的终端屏幕。

下面是一个来自文档的示例工作代码:

use termion::screen::AlternateScreen;
use std::io::{Write, stdout};

fn main() {
    {
        let mut screen = AlternateScreen::from(stdout());
        write!(screen, "Writing to alternate screen!").unwrap();
        screen.flush().unwrap();
    }
    println!("Writing to main screen.");
}

你也可以使用termion在可变备用屏幕上打印。

        write!(
            screen,
            "{}{}{}",
            termion::cursor::Goto(1, 10),
            "some text on coordinates (y=10, x=1)",
            termion::cursor::Hide,
        )
        .unwrap();
//
// to refresh the screen you need to flush it, i.e 
// to write all the changes from the buffer to the screen
// just like flushing to toilet, 
// but flushing the buffer where the text was placed
// which is a matrix
        self.screen.flush().unwrap();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接